Node.js ยท Chapter 30 of 43

Async/Await Patterns

`async`/`await` is modern JavaScript syntax that makes asynchronous code look and read like synchronous code, while still being non-blocking under the hood.

An `async` function always returns a Promise, and `await` pauses execution inside that function until the awaited Promise settles.

Basic usage

Mark a function `async`, then use `await` before any Promise-returning expression to get its resolved value directly.

Error handling

Wrap awaited code in `try/catch` to handle rejected Promises cleanly, similar to handling synchronous exceptions.

Example 1 (javascript)
async function getUser() {
  const res = await fetch('https://api.example.com/user/1');
  const data = await res.json();
  return data;
}
getUser().then(user => console.log(user));
Output
{ id: 1, name: 'Ada' }

await pauses until each Promise resolves, making the flow read top-to-bottom.

Example 2 (javascript)
async function safeCall() {
  try {
    const data = await mightFail();
    console.log(data);
  } catch (err) {
    console.error('Failed:', err.message);
  }
}
Output
Failed: Something went wrong

try/catch handles rejected Promises inside async functions.

Key points

  • async functions always return a Promise.
  • await pauses execution until a Promise settles.
  • try/catch handles errors in async/await code.
  • async/await is syntactic sugar over Promises.
๐Ÿ’ก Note: You can only use `await` inside an `async` function (or at the top level of ES modules).

๐Ÿ“ Quick Quiz

1. What does an async function always return?

2. What does await do?

3. How do you handle errors in async/await code?