liveBook · Manning

Promise.all

As explained in Secrets of the JavaScript Ninja, Second Edition

A JavaScript Promise combinator that returns a promise fulfilled when all input promises fulfill, or rejected if any input promise rejects.

When several independent asynchronous tasks must finish before work can continue, Promise.all waits for every promise in an array. It fulfills with their results in input order, or rejects if any promise rejects. section 6.3.6

Listing 6.17. Waiting for a number of promises with Promise.all
Promise.all([getJSON("data/ninjas.json"),                             #A
             getJSON("data/mapInfo.json"),                            #A
             getJSON("data/plan.json")]).then(results => {            #A
  const ninjas = results[0], mapInfo = results[1], plan = results[2]; #B
                                                                      #B
  assert(ninjas !== undefined                                         #B
 && mapInfo !== undefined && plan !== undefined,                      #B
        "The plan is ready to be set in motion!");                    #B
}).catch(error => {
  fail("A problem in carrying out our plan!");
});

Three JSON requests gather ninja, map, and plan data in parallel; the next step uses their ordered results, with a catch for failure. section 6.3.6

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Specifies array input, fulfillment when all promises succeed, ordered results, and rejection if any promise fails.
Examples
Uses parallel JSON requests for ninja, map, and plan data, then checks the gathered results.
What you can do after
Apply it via Promise.all to wait for multiple asynchronous results and handle their shared success or failure.
How it connects
Connects promises and parallel asynchronous work with Promise.race as an alternative for waiting on the first settled promise.

Also explained in

Compare how 2 books explain Promise.all →

Related concepts

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