Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Creating a Basic Promise | Mastering Promises
Asynchronous JavaScript Explained

bookCreating a Basic Promise

script.js

script.js

index.html

index.html

copy

When you create a new Promise in JavaScript, it starts in the pending state. In the example above, the myPromise object is created using the Promise constructor, which takes a function with two arguments: resolve and reject. Inside this function, you can perform asynchronous operations. Here, a setTimeout is used to simulate a delay. After one second, the resolve function is called with the value "Promise fulfilled!". This action moves the promise from the pending state to the fulfilled state. Once the promise is fulfilled, any .then() handlers attached to the promise will execute, receiving the resolved value. This pattern allows you to write asynchronous code that is easier to read and manage than deeply nested callbacks.

question mark

What does the resolve function do in a Promise?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 2

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Suggested prompts:

Can you explain what happens if the promise is rejected instead of resolved?

Can you show how to handle errors with promises?

What are some real-world use cases for using promises in JavaScript?

Awesome!

Completion rate improved to 3.57

bookCreating a Basic Promise

Sveip for å vise menyen

script.js

script.js

index.html

index.html

copy

When you create a new Promise in JavaScript, it starts in the pending state. In the example above, the myPromise object is created using the Promise constructor, which takes a function with two arguments: resolve and reject. Inside this function, you can perform asynchronous operations. Here, a setTimeout is used to simulate a delay. After one second, the resolve function is called with the value "Promise fulfilled!". This action moves the promise from the pending state to the fulfilled state. Once the promise is fulfilled, any .then() handlers attached to the promise will execute, receiving the resolved value. This pattern allows you to write asynchronous code that is easier to read and manage than deeply nested callbacks.

question mark

What does the resolve function do in a Promise?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 2
some-alt