JavaScript Promises
JavaScript promises represent a value that will be available later, such as the result of a network request or a timer. A promise is pending at first, then becomes fulfilled with a value or rejected with an error.
Why Asynchronous Code?
JavaScript runs on a single thread. If it waited for slow tasks, the page would freeze. Instead, slow work is started and JavaScript continues; the result is handled later. Notice the order of output below.
console.log("1. start");
setTimeout(() => console.log("3. timer done"), 500);
console.log("2. end of script");1. start 2. end of script 3. timer done
Creating a Promise
new Promise takes a function with resolve and reject. Call resolve(value) on success or reject(error) on failure.
function wait(ms) {
return new Promise((resolve) => setTimeout(() => resolve(ms), ms));
}
wait(300).then((ms) => console.log("Waited", ms, "ms"));Waited 300 ms
then, catch and finally
then receives the fulfilled value and returns a new promise, so you can chain steps. catch handles any rejection earlier in the chain.
function checkStock(qty) {
return new Promise((resolve, reject) => {
setTimeout(() => {
qty > 0 ? resolve(qty) : reject(new Error("Out of stock"));
}, 200);
});
}
checkStock(5)
.then((q) => q * 2)
.then((q) => console.log("Double stock:", q))
.catch((e) => console.log(e.message))
.finally(() => console.log("check 1 done"));
checkStock(0)
.then((q) => console.log(q))
.catch((e) => console.log("Failed:", e.message));Double stock: 10 Failed: Out of stock check 1 done
Running Promises in Parallel
- Promise.all: waits for all; rejects as soon as one fails
- Promise.allSettled: waits for all and reports each result
- Promise.race: settles with the first one to finish
- Promise.any: fulfills with the first success
const delay = (v, ms) => new Promise((r) => setTimeout(() => r(v), ms));
Promise.all([delay("A", 300), delay("B", 100), delay("C", 200)])
.then((values) => console.log(values.join(", ")));
Promise.race([delay("slow", 400), delay("fast", 50)])
.then((v) => console.log("race winner:", v));race winner: fast A, B, C
Frequently asked questions
What are the three states of a promise?
Pending, fulfilled and rejected. Once fulfilled or rejected, a promise is settled and never changes again.
What is the difference between Promise.all and Promise.allSettled?
Promise.all rejects as soon as any promise rejects. Promise.allSettled always waits for every promise and gives you each status and value or reason.
Should I use then or async/await?
Both work with promises. async/await usually reads more like normal code, while then is handy for short chains.