CodePark/ questions / Promises & async/await
START PRACTICINGPRACTICE
Frontend question · JavaScript › Promises & async/await

How do async/await work, and how do you handle errors with them?

async function load() {
  try {
    const [user, posts] = await Promise.all([getUser(), getPosts()]);
    return { user, posts };
  } catch (err) {
    console.error("load failed", err);
    throw err;
  }
}

An async function always returns a promise. Inside it, await pauses the function until a promise settles, then continues with the result.

  • Returning a value from an async function fulfills its promise.
  • Throwing inside it rejects its promise.
  • await resumes with the promise's value. If the promise rejects, await throws the rejection reason on that line.

The rest of the program keeps running while the function waits. The engine schedules the resume as a microtask.

Error handling: rejections become thrown errors. So you handle them with normal try/catch/finally around the await. Another way is to call .catch() on the promise that the async function returns.

A promise that you do not await is not covered by the surrounding try.

A common performance mistake is awaiting independent work one after another. Each wait adds to the total time. Start them together and use await Promise.all([a(), b()]) so they run at the same time.

  • async functions always return a promise.
  • await gives the promise's value, or throws its rejection.
  • Use try/catch around await, or .catch() on the returned promise.
  • try only catches promises that you await.
  • Use Promise.all for independent work instead of awaiting one after another.