liveBook · Manning

Promise.all

As explained in Secrets of the JavaScript Ninja, Third Edition

A static Promise method that fulfills with an ordered array of results when all inputs fulfill and rejects if any input rejects.

Promise.all combines an array of promises into one promise. If every input fulfills, the combined promise fulfills with their values in input order. If any input rejects, it rejects immediately with that reason. Use it when concurrent operations are all needed, such as fetching several sources before rendering a UI. section 8.1.3

Listing 8.4 Using Promise.all to combine multiple promises
const allPostsPromise = Promise.all( #A
  [ #B
    fetch("https://jsonplaceholder.typicode.com/posts/1"), #B
    fetch("https://jsonplaceholder.typicode.com/posts/2"), #B
    fetch("https://jsonplaceholder.typicode.com/posts/3"), #B
  ].map((fetchPromise) => #C
    fetchPromise.then((response) => { #C
      if (!response.ok) { #C
        throw new Error(`Status code ${response.status}`); #C
      } #C
      return response.json(); #C
    }), #C
  ), #C
);

allPostsPromise
  .then((posts) => { #D
    posts.forEach((post) => { #D
      console.log(post); #D
    }); #D
  }) #D
  .catch((reason) => { #E
    console.error(`Request failed: ${reason}`); #E
  }); #E

This example fetches three posts concurrently, checks each response, parses the JSON, and handles failure through catch. section 8.1.3

Choose a different combinator when the outcome you need differs:

  • Promise.allSettled waits for every promise to settle and returns each outcome. section 8.1.3
  • Promise.any fulfills with the first fulfilled promise; Promise.race settles with the first promise to settle. section 8.1.3

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains fulfillment order and rejection behavior, then demonstrates concurrent fetches with response checks and JSON parsing.
Examples
Demonstrates fetching three posts concurrently, validating responses, parsing JSON, and logging results or errors.
What it assumes
Builds on promises and chaining while defining promises as placeholders that become fulfilled or rejected.
What you can do after
Apply Promise.all to run independent fetches together and handle their combined result or rejection.
How it connects
Connects Promise.all with promise chaining, Promise.allSettled, Promise.any, and Promise.race.

Also explained in

Compare how 3 books explain Promise.all →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.