Async functions and await
How it works
An async function returns a promise even when its body returns an ordinary value. It begins executing synchronously until it reaches a suspension point. await resolves the operand and resumes the function asynchronously with its fulfillment value, or throws the rejection into the function. A try/catch around await can recover. Suspension affects the async function, not the entire runtime.
Example 1
async function run() { console.log("enter"); const n = await 3; console.log(n); return n * 2; }run().then(console.log);console.log("outside");Expected output in the tested environment:
enteroutside36Even awaiting an ordinary value defers the continuation.
Example 2
async function run() { try { await Promise.reject("bad"); } catch { return 9; } }run().then(console.log);Expected output in the tested environment:
9The catch converts the awaited rejection into a successful return.
Common mistake
Await inside Array.forEach does not cause forEach to wait for callback promises. Use a loop for sequential work or a suitable combinator for concurrent work.
Practice
Rewrite a three-step then chain as an async function, retaining the same returned result and rejection behavior.
Run this practice in the documented local environment. ByteMind module and asynchronous grader support is not yet verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Async functions and await — Knowledge Check
Reason about the concept and predict its behavior in the indicated environment.
What does an async function call return?
What happens when an awaited promise rejects?
Does await block every other task in the host?
For Async functions and await, what is the console output of example 1 in Node.js 22.16.0?
async function run() { console.log("enter"); const n = await 3; console.log(n); return n * 2; }run().then(console.log);console.log("outside");For Async functions and await, what is the console output of example 2 in Node.js 22.16.0?
async function run() { try { await Promise.reject("bad"); } catch { return 9; } }run().then(console.log);