Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Async Patterns for Requests

Async/Await for Requests

Run API requests in sequence or in parallel with async/await, and choose between Promise.all, allSettled, any and race, with live examples and error handling.

A real page rarely needs just one request. A dashboard loads the current user, their orders and a list of notifications. A product page loads the item, reviews and related products. How you combine those requests decides whether the page loads in one second or in four, and whether one failed widget breaks the whole screen.

This lesson builds on async/await from Async/Await and the promise helpers from Promise Combinators. Here we apply them to requests: when to wait for each one, when to start them together, and how errors travel. All servers below are simulated with timers, so every example runs right in the editor.

A mock API with delays

To make timing visible, we use a tiny stand-in for fetch(). It resolves after a delay with a Response, or fails with a network error, depending on the path.

JavaScript
const routes = {
  "/user": { ms: 300, data: { name: "Ada" } },
  "/orders": { ms: 500, data: [101, 102] },
  "/alerts": { ms: 200, data: ["Low stock"] },
  "/broken": { ms: 100, status: 500, data: { error: "Server exploded" } },
};

Each example repeats the same helper, so it stays self-contained. The get() function wraps the response: it checks response.ok (see Handling Errors in fetch) and returns parsed JSON.

Sequential requests

Using await on each line makes the requests run one after another. This is correct when a request depends on the result of the previous one, for instance you need the user id before asking for that user's orders.

JS Sequential requests take the sum of their times

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The total is about one second, the sum of the three delays. If these requests do not depend on each other, that is wasted time.

Parallel requests with Promise.all

Start every request first, then wait. Calling get() returns a promise immediately, so all three run at once, and Promise.all() waits for the slowest.

JS Parallel requests take as long as the slowest

Press Run (or Ctrl + Enter) to see the console output here.

No output.

flowchart LR
    subgraph Sequential["Sequential: 1000 ms"]
        direction LR
        A1["user<br/>300 ms"] --> A2["orders<br/>500 ms"] --> A3["alerts<br/>200 ms"]
    end
    subgraph Parallel["Parallel: 500 ms"]
        direction LR
        B0(["start"]) --> B1["user 300"]
        B0 --> B2["orders 500"]
        B0 --> B3["alerts 200"]
    end

Sequential requests add up to 1000 ms; parallel requests finish after the slowest, 500 ms.

A classic mistake is writing await inside a loop or .map() callback when the requests are independent. That makes them sequential again. Build an array of promises first, then pass the array to Promise.all().

Choosing the right combinator

Promise.all() has a strict rule: one rejection rejects everything, and you lose the results of the others. That suits data the page cannot render without, but not independent widgets. Pick by what a failure should mean:

You need Use Behaviour
Every result, or nothing Promise.all() Rejects as soon as any request fails
Every outcome, success or failure Promise.allSettled() Never rejects; reports each status
The first success (for mirrors) Promise.any() Rejects only if all fail
The first outcome of any kind Promise.race() Settles with the first result or error
JS allSettled keeps the good results

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With Promise.all() the page learns only about the first failure. With Promise.allSettled() you can render the user and the orders and show an error message just in the broken widget.

Mirrors and timeouts: any and race

Promise.any() fits requests that can be satisfied by any of several sources, such as the same file on two servers. It ignores failures until one request succeeds. Promise.race() settles with whichever finishes first, even if that is an error. That makes it a classic way to add a timeout, although cancelling the request with an abort signal is better, as the next lesson shows in Cancelling Requests and Timeouts.

JS Promise.any picks the first success

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Error propagation

An error thrown inside an async function becomes a rejected promise. That rejection travels up through every await until something catches it, so you rarely need a try/catch at each level. A good pattern is to let low-level helpers throw and catch once, near the code that updates the screen. Always remember finally for clean-up such as hiding a spinner:

JavaScript
async function loadDashboard() {
  showSpinner();
  try {
    const [user, orders] = await Promise.all([get("/user"), get("/orders")]);
    render(user, orders);
  } catch (error) {
    showError(error.message);
  } finally {
    hideSpinner();
  }
}

A loading sequence can also be staged: show the essential content as soon as it arrives and fill in slower parts later. Start all requests at once, then await them one by one in the order you want to render them. Because the promises are already running, the second await costs nothing extra if that request has already finished.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Two requests do not depend on each other. How do you make them run in parallel?

    Calling the async functions starts the requests immediately. Promise.all then waits for both, so the total time is the slowest request.
  2. 2. One of three widgets fails, but you still want to show the other two. Which helper fits best?

    allSettled never rejects and tells you the outcome of every request, so you can render the successes and report the failure.
  3. 3. What does Promise.any() do when every promise rejects?

    Promise.any rejects only when all inputs reject, with an AggregateError whose errors array holds each reason.
  4. 4. Where should you usually put try/catch in an async loading function?

    Rejections propagate up through awaits, so one catch where you decide what to show is usually enough.

Summary

  • await one request after another only when a request needs the previous result.
  • Start independent requests together and wait with Promise.all(); the total time is the slowest request.
  • Use allSettled() for independent widgets, any() for mirrors and race() when the first outcome matters.
  • Errors propagate through await; catch near the UI and clean up in finally.

Next: Cancelling Requests and Timeouts.