Skip to content

Promises and async/await, unwrapped

BasicsUnder the hood

You call an async function and the very next line runs before its body has finished, yet nothing ever blocks. Here is what a promise really is, and what await does to your function, drawn one step at a time.

01 The line after the call runs first

load waits 100 ms for a number. Read the numbers in the log messages: they show the order you might expect. Then look at what load() actually hands back on line 3.

order.mjs
function getNumber() {
return new Promise((resolve) => setTimeout(() => resolve(21), 100));
}
async function load() {
console.log('2: load starts');
const n = await getNumber();
console.log('4: got', n);
return n * 2;
}
console.log('1: before load()');
const p = load();
console.log('3: load() returned', p);
p.then((v) => console.log('5: result', v));
Shell
node order.mjs
Text
1: before load()
2: load starts
3: load() returned Promise { <pending> }
4: got 21
5: result 42

That output is a real run on Node 24. load() returned before its body reached return, and what came back was not 42 but a Promise in the pending state. The script went on to line 3 while load was, somehow, still half done.

02 await does not block

A common first picture is that await makes the program stop and wait, like sleep in other languages. It cannot: JavaScript runs your code on one thread, and if that thread stopped, nothing else (clicks, timers, other requests) could run either.

If await blockedEverything stopsThe whole thread would sit idle for 100 ms, and line 3 could not run until the number arrived.
What await doesOnly load pausesload is set aside with its local variables, the caller carries on, and load resumes later from the same spot.

03 A promise is a box with a state and a list

A promise is an ordinary object that stands for a result which may not exist yet. It holds three things: a state, a value once there is one, and a list of waiters, the callbacks to run when it settles.

The three states of a promise
StateValueWhat happens to waiters
pendingnone yetThey are stored in the list.
fulfilledthe resultEach one is queued as a microtask with the value.
rejectedthe errorEach error handler is queued as a microtask with the error.

A promise settles once. After it is fulfilled or rejected, calling resolve or reject again does nothing. A waiter added later, with .then on a promise that has already settled, is queued straight away. Either way the callback never runs in the middle of your current code: it waits in the microtask queue until the code on the stack has finished.

The function you pass to new Promise(fn) runs synchronously, right inside the constructor. Only the callbacks given to .then, .catch, .finally and the code after an await are delayed.

04 What await does to your function

To watch it closely, take a smaller program with no timer. The promise ready is settled by hand with resolveIt, so every step is in the code below.

await.mjs
let resolveIt;
const ready = new Promise((resolve) => {
resolveIt = resolve;
});
async function load() {
console.log('load starts');
const n = await ready;
console.log('got', n);
return n * 2;
}
const result = load();
console.log('load returned');
resolveIt(21);
result.then((v) => console.log('result', v));
One await, step by step
Step 1 of 13
Call stack
scripttop
Promises · their state and waiters
Empty
Microtask queue
Empty
Logged
Empty
  • just added
  • running or just changed
  • just settled

The script starts. It is the only thing on the stack. No promise exists yet and nothing is queued.

Two facts carry the whole picture. An async function always returns a promise at once, at its first await or at its end, whichever comes first. And await p means: put the rest of this function on p’s waiter list, then return to whoever called me. The function’s frame really does leave the stack; the engine keeps its local variables and its place in a separate object until the resume runs.

05 async/await is promises with nicer syntax

Every await splits the function in two: the part before it and a callback for the part after. You can write the same load by hand with .then.

async/await
async function load() {
console.log('load starts');
const n = await ready;
console.log('got', n);
return n * 2;
}
the same with then
function load() {
console.log('load starts');
return ready.then((n) => {
console.log('got', n);
return n * 2;
});
}

This is close, not exact: an await inside a loop or a try block would need much more code to write by hand, which is why the syntax exists. But the order of the logs and the returned promise are the same. Even await on a plain value, such as await 0, splits the function: the rest still runs as a microtask, after the current code.

JavaScript
async function f() {
console.log('1');
await 0;
console.log('3');
}
f();
console.log('2');
// 1 2 3

06 Errors travel through the promise

A throw inside an async function does not escape to the caller. It rejects the function’s promise instead. In the other direction, await on a rejected promise throws the error at that line, so an ordinary try/catch around the await catches it.

errors.mjs
async function save() {
throw new Error('disk full');
}
try {
save(); // no await: the error is not caught here
} catch (e) {
console.log('never runs');
}
try {
await save(); // await turns the rejection back into a throw
} catch (e) {
console.log('caught:', e.message);
}
Shell
node errors.mjs; echo "exit $?"
Text
caught: disk full
Error: disk full
at save (…/errors.mjs:2:9)
at …/errors.mjs:6:3
exit 1

That is a real run on Node 24, with the stack trace shortened. The second call is caught. The first call’s rejection had no handler, so once the program was otherwise idle Node reported an unhandled rejection: since Node 15 the default is to print the error and exit with code 1. Browsers log it to the console and keep going.

07 When it bites

const user = getUser(id); console.log(user.name); // undefinedForgetting awaituser is a promise, not the user. Promises have no name, so you get undefined rather than an error. TypeScript catches this one, because a Promise<User> has no name property.
ids.forEach(async (id) => { await save(id); }); console.log('all saved?'); // runs firstawait inside forEachforEach ignores the promises its callback returns, so nothing waits for them. Use for (const id of ids) await save(id); to go one by one, or await Promise.all(ids.map(save)) to run them together.
const a = await fetchA(); const b = await fetchB();Waiting in turn when you need notfetchB does not start until fetchA has finished. If they do not depend on each other, start both first: const [a, b] = await Promise.all([fetchA(), fetchB()]);.
save(); // returns a rejected promiseA rejection nobody handlesWithout await or .catch, the error has nowhere to go. In Node this crashes the process. Always await a promise, return it, or attach .catch.

await pauses only the async function it is written in. Its caller keeps running unless the caller also awaits. A missing await one level up is the most common reason code runs “too early”.

08 Check yourself

Question

async function f() { return 5; } What does f() return?

Question

What does this log? Promise.resolve().then(() => console.log('a')); console.log('b');

Question

While an async function is paused at await, where is its frame?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?