Skip to content
KALANBLON
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.

Step 6 of 6
Text description of the animation
  1. The main code runs line by line.
  2. setTimeout doesn't run anything right away: it puts its function in the task queue, even with 0 ms.
  3. The promise's continuation goes into the microtask queue, which has priority.
  4. The main code finishes: the event loop takes over.
  5. It first empties all the microtasks…
  6. …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: call resolve(value) on success, reject(error) on failure. In practice you rarely create one yourself: fetch and most APIs already return them.
  • await loadProfile(id) waits for the result. If the promise is rejected, await throws the error, which you catch with an ordinary try/catch.
  • finally runs in every case: ideal for hiding a loading indicator.
  • In this course's labs, your code runs inside an async function: you can write await directly, as here. In a classic JavaScript file, await outside an async function 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
FunctionWaits for…On error
Promise.all([…])every promisefails at the first error
Promise.allSettled([…])all of them, whatever happensnever fails: each result says fulfilled or rejected
Promise.race([…])the first one to settlefails if the first one to settle is an error
Promise.any([…])the first one fulfilledfails 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
Create a second promise that is rejected after 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.message is then undefined. Always reject with an Error object.

Summary

  1. 1The event loop runs the main code first, then promise continuations, then timers.
  2. 2An async function returns a promise; await waits for its result without blocking the page.
  3. 3A rejected promise makes await throw: try, catch and finally work as usual.
  4. 4Promise.all waits for everything in parallel, allSettled never fails, race keeps the first answer.
  5. 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.