JavaScript

This page explains how await waits for a Promise result so asynchronous code can be read in a clear, top-to-bottom order.

Goal: use await inside an async function, handle failures with try...catch, and choose Promise.all() when work can run in parallel.

await

await pauses the current async function until a Promise settles. It does not block the browser or stop unrelated work. The function resumes with the fulfilled value, or throws when the Promise rejects.

Basic usage

JavaScript

async function fetchData() {
  const response = await fetch("https://example.com/data.json");
  const data = await response.json();
  console.log(data);
}

The function waits for the response, then waits for the JSON body. An await expression is normally used inside an async function, with top-level await available in supported modules.

Handle failures

JavaScript

async function loadUser() {
  try {
    const response = await fetch("/user");
    if (!response.ok) throw new Error("Request failed");
    return await response.json();
  } catch (error) {
    console.error("Could not load the user", error);
    return null;
  }
}

fetch() does not reject just because the server returns 404 or 500, so check response.ok when HTTP errors matter.

Serial or parallel?

Awaiting inside a loop starts the next operation only after the previous one finishes. When requests do not depend on one another, start them first and await them together.

JavaScript

const results = await Promise.all(
  urls.map(url => fetch(url).then(response => response.json()))
);

Related topics