JavaScript ยท Chapter 51 of 55

JavaScript Async & Await

`async`/`await` is modern syntax built on top of Promises that lets asynchronous code read almost like synchronous code, improving readability significantly.

An `async` function always returns a Promise, and inside it, `await` pauses execution until the awaited Promise settles, without blocking the rest of the browser.

async functions

Adding `async` before a function definition means it always returns a Promise, and lets you use `await` inside it.

await and error handling

`await promise` pauses the async function until the promise resolves, returning its value. Wrap awaited code in try/catch to handle rejections.

Example 1 (javascript)
async function getValue() {
  return 42;
}
getValue().then(v => console.log(v));
Output
42

An async function automatically wraps its return value in a resolved Promise.

Example 2 (javascript)
async function run() {
  let result = await Promise.resolve("done");
  console.log(result);
}
run();
Output
done

await pauses until the Promise resolves, then returns its value directly.

Key points

  • async functions always return a Promise.
  • await pauses execution until a Promise settles.
  • try/catch around await handles rejected Promises.
  • async/await makes asynchronous code look synchronous and readable.
๐Ÿ’ก Note: await can only be used inside functions marked async (or at the top level of modern 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?