Show contents
Chapter 1 of 6 · 20 min
Promises and async/await
By the end of this chapter, you'll be able to
- Predict the execution order of synchronous code, promises and timers
- Write async functions and wait for their result with await
- Handle asynchronous errors with try, catch and finally
- Run several operations in parallel with Promise.all, allSettled and race
One task at a time, but never blocked
JavaScript runs one piece of code at a time. Long operations (timers, network requests) are handed to the browser, which notifies JavaScript when they finish. The code that must run next waits in a queue, and the event loop runs it as soon as the current code is done.
console.log("1. start");
setTimeout(() => console.log("4. timer (0 ms)"), 0);
Promise.resolve().then(() => console.log("3. promise resolved"));
console.log("2. end of main code");
1. start
2. end of main code
3. promise resolved
4. timer (0 ms)
…then runs the next task: the timer.
Text description of the animation
- The main code runs line by line.
- setTimeout doesn't run anything right away: it puts its function in the task queue, even with 0 ms.
- The promise's continuation goes into the microtask queue, which has priority.
- The main code finishes: the event loop takes over.
- It first empties all the microtasks…
- …then runs the next task: the timer.
Promises and async/await
A promise (Promise) represents a result that isn't there yet. It ends up either fulfilled (with a value) or rejected (with an error). A function marked async always returns a promise, and await waits for a promise to settle without blocking the rest of the page:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function loadProfile(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id <= 0) reject(new Error(`profile ${id} not found`));
else resolve({ id, name: id === 1 ? "Amina" : "Tomás" });
}, 100);
});
}
async function show(id) {
try {
const profile = await loadProfile(id);
console.log(`Hello ${profile.name}`);
} catch (error) {
console.log(`Error: ${error.message}`);
} finally {
console.log(`(request ${id} done)`);
}
}
await show(1);
await show(0);
await wait(50);
console.log("finished");
Hello Amina
(request 1 done)
Error: profile 0 not found
(request 0 done)
finished
new Promise((resolve, reject) => …)creates a promise: callresolve(value)on success,reject(error)on failure. In practice you rarely create one yourself:fetchand most APIs already return them.await loadProfile(id)waits for the result. If the promise is rejected,awaitthrows the error, which you catch with an ordinarytry/catch.finallyruns in every case: ideal for hiding a loading indicator.- In this course's labs, your code runs inside an
asyncfunction: you can writeawaitdirectly, as here. In a classic JavaScript file,awaitoutside anasyncfunction is only allowed in a module.
Several operations at once
Waiting for two requests one after the other adds up their durations. Starting them together and waiting for both costs only the longest:
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, message) => new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
let start = Date.now();
const [a, b] = await Promise.all([wait(200, "weather"), wait(200, "traffic")]);
console.log(a, b, "in parallel:", Date.now() - start < 350);
const results = await Promise.allSettled([wait(50, "calendar"), fail(80, "bus service down")]);
for (const r of results) {
console.log(r.status === "fulfilled" ? `ok: ${r.value}` : `failed: ${r.reason.message}`);
}
const first = await Promise.race([wait(300, "slow server"), wait(100, "fast server")]);
console.log("first to arrive:", first);
try {
await Promise.all([wait(50, "x"), fail(60, "one error is enough")]);
} catch (e) {
console.log("Promise.all failed:", e.message);
}
weather traffic in parallel: true
ok: calendar
failed: bus service down
first to arrive: fast server
Promise.all failed: one error is enough
| Function | Waits for… | On error |
|---|---|---|
Promise.all([…]) | every promise | fails at the first error |
Promise.allSettled([…]) | all of them, whatever happens | never fails: each result says fulfilled or rejected |
Promise.race([…]) | the first one to settle | fails if the first one to settle is an error |
Promise.any([…]) | the first one fulfilled | fails only if all fail |
Your turn
Mini-lab: breakfast in parallelJavaScript
Output
Click “Run” to execute your code.Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Solved exercise: a timeout
Write a function withTimeout(promise, ms) that returns a promise: it is fulfilled with the value of promise if that arrives in time, and rejected with the error "timed out after … ms" otherwise. Remember to stop the timer when it's no longer needed.
Hint 1
ms milliseconds, then race the two with Promise.race.Hint 2
promise.finally(() => clearTimeout(timer)) stops the timer in every case.Show the solution and common mistakes
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
function withTimeout(promise, ms) {
let timer;
const deadline = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`timed out after ${ms} ms`)), ms);
});
return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));
}
console.log(await withTimeout(wait(50, "fast answer"), 200));
try {
await withTimeout(wait(500, "slow answer"), 100);
} catch (e) {
console.log("Error:", e.message);
}
fast answer
Error: timed out after 100 ms
The slow promise isn't cancelled, though: it carries on in the background, and its result is simply ignored. To really interrupt a network request, you use an AbortController, introduced in the next chapter.
Common mistakes:
- Forgetting
clearTimeout: the timer keeps running after a fast answer. On a page that makes hundreds of requests, these timers pile up for nothing. - Writing
reject("timed out")with a plain string:e.messageis thenundefined. Always reject with anErrorobject.
Summary
- 1The event loop runs the main code first, then promise continuations, then timers.
- 2An async function returns a promise; await waits for its result without blocking the page.
- 3A rejected promise makes await throw: try, catch and finally work as usual.
- 4Promise.all waits for everything in parallel, allSettled never fails, race keeps the first answer.
- 5Don't use await inside forEach: prefer for…of or Promise.all with map.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.