JavaScript Promises
A promise is a value that stands for a result still on its way. The result arrives later, and the promise carries it to the code that waits for it.
A promise that resolves after a wait
The promise below fulfills with a message after a short timer. The then method runs its function once the message arrives.
const p = new Promise((resolve) => {
setTimeout(() => resolve("Dinner is ready"), 50);
});
p.then((message) => console.log(message));Code keeps running while a promise waits
The script does not stop for the promise. The two plain lines print first, and the message from the promise prints last.
console.log("Cooking starts");
const p = new Promise((resolve) => {
setTimeout(() => resolve("Dinner is ready"), 50);
});
p.then((message) => console.log(message));
console.log("Cooking continues");A promise that is already fulfilled
A promise can fill at once, with no timer. The then function still runs after the plain lines, never in the middle of them.
const p = new Promise((resolve) => {
resolve(42);
});
console.log("Before");
p.then((value) => console.log(value));
console.log("After");Example
function delivery() {
return new Promise((resolve) => {
setTimeout(() => resolve("Package delivered"), 50);
});
}
console.log("Order placed");
delivery().then((message) => console.log(message));
console.log("Waiting for the package");Key points
- Promise: a value that stands for a result that arrives later
- Pending: the state of a promise while its result is still on the way
- Fulfilled: the state of a promise that finished with a value
- Rejected: the state of a promise that finished with an error
- resolve: the function that fulfills a promise with a value
- reject: the function that rejects a promise with an error
- then: a method that runs a function when the promise fulfills
In this example, the delivery function builds a promise that fills after a short timer. The first log line runs at once. The waiting line runs next. The then method logs the delivery message once the timer finishes.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does a promise stand for?