How to use Promise.all and Promise.race

· Category: Node.js

Short answer

Promise.all waits for all promises to resolve and returns their results as an array, failing fast if any reject. Promise.race returns the result of the first promise to settle, whether it resolves or rejects.

Steps

  1. Create an array of promises.
  2. Use const results = await Promise.all([p1, p2, p3]);.
  3. Use const winner = await Promise.race([p1, p2, p3]);.
  4. Handle rejections with try/catch or .catch().
  5. For partial failure tolerance, consider Promise.allSettled.

Tips

  • Promise.all is ideal when you need every result before continuing, such as aggregating API responses.
  • Promise.race is useful for timeouts: Promise.race([fetchData(), sleep(5000).then(() => { throw new Error('Timeout'); })]).

Common issues

  • If one promise in Promise.all rejects, the others continue running but their results are lost unless handled individually.
  • Promise.race resolves or rejects with the first settled promise, which may be an error you did not expect.