← Back to Node.js Course | Chapter 4: Async Programming | Lesson 3 of 7

async/await

async/await lets you write promise code so it reads like ordinary top-to-bottom code.

In this page:

  1. async/await
Syntax
javascript
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

javascript
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
  1. Forgetting await and getting a Promise object
  2. Using await in a loop when calls could run in parallel
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.