liveBook · Manning

Concurrency

As explained in Secrets of the JavaScript Ninja, Third Edition

Concurrency is the overlapping progress of multiple operations during the same period of execution.

When a UI needs data from several sources, sending requests concurrently avoids waiting for each request to finish before starting the next. JavaScript promises let you combine those operations and handle their outcomes together. section 8.1.3

Choose a promise combinator based on how the results should be handled:

  • Promise.all fulfills with values in input order when every promise fulfills; it rejects as soon as one rejects. section 8.1.3
  • Promise.allSettled fulfills after every promise settles, reporting each outcome; Promise.any fulfills with the first fulfillment; Promise.race adopts the first settlement, fulfilled or rejected. 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

See multiple fetch requests combined with Promise.all, including response checks and shared error handling. section 8.1.3

Listing 8.5 Using Promise.race to enforce a timeout
const fetchController = new AbortController(); #A
 
const fetchPromise = fetch("https://httpbin.org/delay/2", { #B
  signal: fetchController.signal, #B
}).then((response) => { #B
  if (!response.ok) { #B
    throw new Error(`Status code ${response.status}`); #B
  } #B
  return response.json(); #B
});
 
const timeoutPromise = new Promise((_, reject) => #C
  setTimeout(() => { #C
    fetchController.abort(); #C
    reject(new Error("Request timeout"));
  }, 1_000), #C
); #C
 
Promise.race([fetchPromise, timeoutPromise]) #D
  .then((result) => {
    console.log(result);
  })
  .catch((reason) => {
    console.error(`Request failed: ${reason}`);
  });

See Promise.race paired with AbortController to enforce a request timeout. section 8.1.3

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains four Promise combinators through their outcome behavior and fetch examples.
Examples
Uses multiple post requests with Promise.all and a fetch timeout with Promise.race.
What it assumes
Assumes familiarity with promises and chaining, and builds on those basics to handle concurrent operations.
What you can do after
Apply Promise.all to combine concurrent fetches or Promise.race to enforce a timeout.
How it connects
Connects concurrency to promises, promise chaining, fetch, and AbortController.

Also explained in

Compare how 31 books explain concurrency →

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.