Lesson 16 of 28
In progress
Promises: the value that arrives later
Understand pending, fulfilled and rejected states, chain work with then, and wait for several promises together.
A promise is an object representing a value that is not ready yet. fetch returns one, response.json() returns one, and every await is built on top of them.
What you will learn
- Recognise the three promise states.
- Chain work with
then,catchandfinally. - Wait for several promises with
Promise.allandallSettled.
Three states
A promise is pending, then either fulfilled with a value or rejected with a reason. Once settled, it never changes again.
Editable. Runs in your browser.
resolved.then((value) => console.log("fulfilled:", value));
rejected.catch((error) => console.log("rejected:", error.message));
Press Run to see the output.
Creating promises with resolve and reject is mostly for wrapping older callback APIs. Application code usually receives promises from fetch, timers and libraries rather than constructing them.
then, catch, finally
then schedules a function for the fulfilled value. It returns a new promise, which is what allows chaining.
Editable. Runs in your browser.
Press Run to see the output.
Returning a value passes it to the next then. Returning a promise waits for that promise, which is how chained requests work without nesting. catch handles a rejection anywhere above it in the chain, so one handler at the end is often enough.
finally runs on both paths and receives no value. It is for cleanup, such as hiding a spinner or clearing a timer.
Throwing inside then rejects the chain:
Editable. Runs in your browser.
Press Run to see the output.
Wrapping a callback
Older APIs take a callback instead of returning a promise. Wrapping them once makes the rest of the code consistent.
Editable. Runs in your browser.
delay(20).then(() => console.log("20ms later"));
Press Run to see the output.
The executor function runs immediately and receives resolve and reject. Call exactly one of them; later calls are ignored. If the operation can fail, call reject(new Error(...)) and make sure the error carries a useful message rather than a string.
Promises are also useful for turning an event into a one-time await, such as waiting for an image to load:
Editable. Runs in your browser.
console.log(typeof loaded);
Press Run to see the output.
{ once: true } removes the listener after it fires, so the promise does not leak handlers.
A rejected promise with no handler produces an unhandledrejection event and a console warning. Attaching a catch at the end of a chain, or awaiting inside try, is what keeps those warnings out of a shipped page. finally does not change the value or the rejection; it only runs cleanup and passes the outcome along unchanged.
Waiting for several
Editable. Runs in your browser.
Promise.all([slow("a", 100), slow("b", 50), slow("c", 10)])
.then((values) => console.log(values));
Press Run to see the output.
Promise.all resolves when every promise resolves, preserving input order regardless of completion order. It rejects as soon as any promise rejects, which is right when all results are required.
Promise.allSettled waits for every promise and gives each outcome separately, which is right for independent tasks where one failure should not hide the rest.
Editable. Runs in your browser.
Press Run to see the output.
Promise.race settles with the first promise to settle, which is useful for timeouts. Promise.any resolves with the first fulfilment and rejects only if all fail.
Sequential versus parallel
Editable. Runs in your browser.
await slow("a", 120);
await slow("b", 120);
console.log("sequential:", Math.round(performance.now() – start));
const start2 = performance.now();
await Promise.all([slow("a", 120), slow("b", 120)]);
console.log("parallel:", Math.round(performance.now() – start2));
}
timed();
Press Run to see the output.
Sequential awaits take the sum of the delays; Promise.all takes the longest. Use parallel when the requests are independent, and sequential when one depends on the result of another.
Forgetting to return
Editable. Runs in your browser.
Press Run to see the output.
The second then receives undefined, because the first callback did not return the promise. The fix is a single word: return slow(...). This is the most common promise bug in code that mixes arrows with braces.
array.forEach(async (item) => { await save(item); }) does not wait for anything: forEach ignores the returned promises, so the code after the loop runs before the saves finish. Use for...of with await for sequential work, or Promise.all(array.map(...)) for parallel work.
Create wait(ms, value) returning a promise that resolves after ms. Use Promise.all to wait for three different delays, then log the values and the total elapsed time.
Show solution
Editable. Runs in your browser.
async function run() {
const start = performance.now();
const values = await Promise.all([wait(60, "a"), wait(30, "b"), wait(90, "c")]);
console.log(values);
console.log("elapsed:", Math.round(performance.now() – start));
}
run();
Press Run to see the output.
The values come back in input order even though they finish at different times, and the total is close to the longest delay rather than the sum.
Recap
- A promise is pending, then fulfilled or rejected, once.
thenchains and transforms;catchhandles any rejection above it;finallycleans up.Promise.allfails fast,allSettledreports every outcome, andracetakes the first.
Next, you will write asynchronous code in the async/await style, which reads like synchronous code.
What is a thenable?
Can I cancel a promise?
Progress is saved in this browser only. No account, no email.