async and await

async and await are the same promises with the shape of ordinary code. An async function returns a promise, and await inside it waits for one to settle and gives back its value, so a chain of then calls becomes a list of statements that reads from top to bottom.

The lesson takes the keyword, the pause it creates, the try that catches a rejected await as if it were a throw, and the one difference that matters in practice: a loop with an await runs one call at a time, and Promise.all under a map runs them together.

An async function returns a promise

A function marked async always returns a promise: a returned value fulfils it and a thrown error rejects it. Nothing else changes about the body, and a caller that ignores the promise gets no value at all, only the promise object.

The file async.mjs:

async function answer() { return 42; } async function fail() { throw new Error('the async call failed'); } const promise = answer(); console.log('the call returns a promise:', promise instanceof Promise); console.log('the value arrives here:', await promise); try { await fail(); } catch (error) { console.log('a throw inside async rejects:', error.message); }

node async.mjs

the call returns a promise: true
the value arrives here: 42
a throw inside async rejects: the async call failed

The value 42 never travelled as a return value: it fulfilled the promise, and the caller read it with await. The second call threw, and the throw arrived as a rejection, which is why the same try that catches a synchronous error catches this one too.

await pauses the function

await suspends the async function and returns control to its caller, which carries on with the next line. The function resumes as a microtask when the promise settles, which is why the caller can print between the two halves of the callee.

The file await.mjs:

const delay = (value, ms) => new Promise((resolve) => { setTimeout(() => resolve(value), ms); }); async function slow() { console.log('slow: before the await'); const value = await delay('the value', 10); console.log('slow: after the await', value); return value; } const running = slow(); console.log('the caller keeps going'); await running; console.log('the caller joins at the end');

node await.mjs

slow: before the await
the caller keeps going
slow: after the await the value
the caller joins at the end

The call to slow returned a promise at the first await, and the program printed its own line in the gap. The final await joined the two halves, the way a then would have. Only the function pauses: the thread is free for other work in between.

try and catch around await

A rejected await throws at the await, so the code that handles it is the ordinary try statement. That is the reason to prefer this form over a chain for anything with more than two steps: the failure path is in one place and the happy path is not indented.

The file tryAwait.mjs:

async function load(name) { if (name === '') { throw new Error('the name is empty'); } return `loaded ${name}`; } async function report(name) { try { return await load(name); } catch (error) { return `failed: ${error.message}`; } finally { console.log('attempted:', name === '' ? '(empty)' : name); } } console.log(await report('notes.txt')); console.log(await report(''));

node tryAwait.mjs

attempted: notes.txt
loaded notes.txt
attempted: (empty)
failed: the name is empty

Each call printed its finally line before the value of the function, and the failure became a returned string rather than a throw at the top. The same structure catches a network failure, a missing file or a rejected promise of any other kind, because all of them arrive at the await as a throw.

One at a time or all at once

An await in a loop waits for each call before starting the next, which is right when the second depends on the first and wrong when the calls are independent. The two halves of the program below do the same work, and only the second starts everything at once; the log lines show the difference in the order of the starts.

The file parallel.mjs:

const delay = (value, ms) => new Promise((resolve) => { setTimeout(() => resolve(value), ms); }); async function fetchOne(name) { console.log('start', name); const value = await delay(name, 10); console.log('end', name); return value; } const sequential = []; for (const name of ['a', 'b']) { sequential.push(await fetchOne(name)); } console.log('one at a time:', sequential.join(',')); const together = await Promise.all(['a', 'b'].map((name) => fetchOne(name))); console.log('all at once:', together.join(','));

node parallel.mjs

start a
end a
start b
end b
one at a time: a,b
start a
start b
end a
end b
all at once: a,b

The first half printed start a, end a, start b: the second call did not begin until the first was done. The second half printed both starts before either end, so the two waits overlapped. Both returned the same values, and only the order of the work changed, which is why the shape of the loop is the decision that matters in a program that makes many calls.

Exercises

  1. Call answer() without await and print the value. What does a promise print as?
  2. Add a third step to the chain of the second program and print its value.
  3. Make report rethrow the error after the finally line. Which line reaches the top of the program?
  4. Add a third name to the loop of the last program and count the start lines in each half.
  5. Replace the loop with Promise.all over the same array and compare the number of lines. Which shape would you use for twelve independent calls?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does an async function return?

    Answer

    A promise

    The async keyword wraps the return value in a promise, whether the value is used or not.

  2. What does await do?

    Answer

    It pauses the async function until the promise settles

    Only the function is suspended, and the rest of the program keeps running.

  3. What does a throw inside an async function do?

    Answer

    It rejects the promise the function returned

    The throw becomes the reason of the rejection, and await turns it back into a throw for the caller.

  4. Which code waits for three independent calls one after another?

    Answer

    A for loop with await inside

    The loop awaits each call before the next one starts, while all and race start them together.

  5. What does this program print? async function f() { return 1; } f().then((value) => console.log(value)); console.log("outside");

    Answer

    outside / 1

    The then callback is a microtask, so the synchronous line comes first.

  6. What does this program print? async function f() { throw new Error("bad"); } try { await f(); } catch (error) { console.log(error.message); }

    Answer

    bad

    The rejection arrives at the await as a throw, and the catch prints its message.

  7. What does this program print? const value = await Promise.resolve(2).then((n) => n * 3); console.log(value);

    Answer

    6

    The await unwraps the promise that the then returned, whose value is six.

  8. How do you start three independent async calls at once?

    Answer

    Promise.all over the three calls

    The calls must be made before anything is awaited, and all takes the promises as an array.

  9. What does this program print? async function f() { console.log("a"); await null; console.log("b"); } await f(); console.log("c");

    Answer

    a / b / c

    The await of the caller waits for the function to finish, so its last line comes after b.

  10. Which shape is right for twelve independent calls?

    Answer

    Promise.all over twelve calls

    Independent calls can overlap, and all waits for the slowest of them.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev