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
- Create an array of promises.
- Use
const results = await Promise.all([p1, p2, p3]);. - Use
const winner = await Promise.race([p1, p2, p3]);. - Handle rejections with try/catch or
.catch(). - For partial failure tolerance, consider
Promise.allSettled.
Tips
Promise.allis ideal when you need every result before continuing, such as aggregating API responses.Promise.raceis useful for timeouts:Promise.race([fetchData(), sleep(5000).then(() => { throw new Error('Timeout'); })]).
Common issues
- If one promise in
Promise.allrejects, the others continue running but their results are lost unless handled individually. Promise.raceresolves or rejects with the first settled promise, which may be an error you did not expect.