JavaScript path · Async · Topic 7 of 12

async / await

Not started

An async function always returns a promise. Code before the first await runs straight away; at an await the function pauses, and the rest of it resumes as a microtask once the awaited value has settled. Awaiting things one after another runs them in sequence; start them together and use Promise.all to run them in parallel.

Why it matters: Accidental sequential awaits are one of the most common reasons an API handler is slower than it needs to be.

1

How it works

The explanation, with examples you can run.

Sequential or parallel

⌘/Ctrl + Enter
OutputNot run yet

Press Run to see what your code prints, in order.

Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.

Awaiting in a loop has the same effect: for (const id of ids) await load(id) loads one at a time. That is right when each step needs the previous one, or when you must go easy on a server; otherwise map to promises first and await them together.

Errors

A rejected promise makes await throw, so ordinary try/catch works. One trap: inside try, write return await work() rather than return work(); without the await, the function returns before the promise settles and your catch never sees the failure.

⌘/Ctrl + Enter
OutputNot run yet

Press Run to see what your code prints, in order.

Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.

In ES modules (and in Node's .mjs files) you can also use await at the top level, outside any function.

2

Check yourself

2 questions. Get them all right to finish this topic.

  1. 1.An async function's body runs `return 5`. What does calling it give you?
  2. 2.Two independent requests take about 200 ms each. How long does `await a(); await b()` take?

0 of 2 right so far. Get all two to finish this topic.