async/await
async/await lets you write promise code so it reads like ordinary top-to-bottom code.
In this page:
Syntax
async function functionName() {
try {
const result = await promiseReturningCall();
} catch (err) {
// handle err
}
}
async/await
An async function always returns a promise. await pauses the function until a promise settles, returning its value or throwing its rejection, which you handle with try/catch. Top-level await works in ES modules.
Note:
await only pauses the async function, not the whole program.
Example: async/await
const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
async function main() {
try {
const a = await delay(5, "first");
const b = await delay(5, "second");
console.log(a, b);
await Promise.reject(new Error("boom"));
} catch (e) {
console.log("caught:", e.message);
}
}
main();
// Output:
// first second
// caught: boom
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Forgetting await and getting a Promise object
- Using await in a loop when calls could run in parallel
- Forgetting try/catch
Chapter Summary
- async functions return promises
- await unwraps a promise
- Use try/catch for errors
- await only pauses its own function
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: