Hone

Lessons · JavaScript · async / await

await pauses only its own function

await inside an async function pauses that function until the promise settles. Everything outside it keeps running, which is the whole point.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

The page stays responsive while data loads because await does not block the world. Misreading it as a global pause is how people write code that assumes data has arrived when it has not.

How to think about it

Read an async function top to bottom, but remember that at each await, the rest of the program runs. Start independent work first and await Promise.all, rather than awaiting one at a time.

Worked example

const wait = ms => new Promise(r => setTimeout(r, ms));
A promise that settles after ms.
async function run() { console.log("a"); await wait(10); console.log("c"); }
Pauses after a.
run();
Starts, logs a, pauses at the await.
console.log("b");
Runs while run is paused: a, b, c.

Your turn

Wait for the user to load.

const user =  getUser(id);

The trap

await in a loop runs the calls one after another. For independent work, start all the promises first and await Promise.all.

Practise async / await on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.