乐闻世界logo
搜索文章和话题

What is the difference between Promise.all() and Promise.race()?

2月22日 14:07

Promise.all() and Promise.race() are two important static methods provided by Promise, used for handling parallel execution of multiple Promises, but their behaviors and use cases are completely different.

Promise.all()

Basic Concept

Promise.all() accepts an array of Promises as a parameter and returns a new Promise. This new Promise will only succeed when all input Promises have successfully completed, returning an array of all Promise results (in the same order as input). If any Promise fails, Promise.all() will immediately fail, returning the error of the first failed Promise.

Use Cases

  • Need to initiate multiple independent requests simultaneously and wait for all requests to complete
  • There are dependencies between multiple asynchronous operations, need all results to be ready before continuing

Example Code

javascript
const promise1 = fetch('/api/user'); const promise2 = fetch('/api/posts'); const promise3 = fetch('/api/comments'); Promise.all([promise1, promise2, promise3]) .then(responses => { // All requests successful return Promise.all(responses.map(r => r.json())); }) .then(data => { console.log('All data:', data); }) .catch(error => { console.error('Some request failed:', error); });

Features

  1. Parallel execution: All Promises start executing simultaneously
  2. Order guarantee: Result array order matches input order
  3. Fast fail: If any fails, the entire operation fails immediately
  4. Empty array: If an empty array is passed, returns success immediately

Promise.race()

Basic Concept

Promise.race() also accepts an array of Promises and returns a new Promise. This new Promise will complete immediately when the first Promise completes (whether successful or failed), returning the result or error of the first completed Promise.

Use Cases

  • Setting timeout mechanisms
  • Getting data from multiple sources, using the fastest returned result
  • Handling race conditions

Example Code

javascript
// Timeout example const fetchData = fetch('/api/data'); const timeout = new Promise((_, reject) => { setTimeout(() => reject(new Error('Request timeout')), 5000); }); Promise.race([fetchData, timeout]) .then(response => console.log('Data fetch successful')) .catch(error => console.error(error)); // Multi-source competition example const source1 = fetch('https://api1.example.com/data'); const source2 = fetch('https://api2.example.com/data'); const source3 = fetch('https://api3.example.com/data'); Promise.race([source1, source2, source3]) .then(response => response.json()) .then(data => console.log('Fastest data source:', data));

Features

  1. Fast return: Returns the first completed result
  2. State inheritance: Success or failure depends on the first completed Promise
  3. Uncertainty: Which Promise completes first is uncertain
  4. Empty array: If an empty array is passed, the Promise remains in pending state forever

Comparison Summary

FeaturePromise.all()Promise.race()
Completion conditionAll Promises succeedFirst Promise completes
Failure conditionAny Promise failsFirst Promise fails
Return resultArray of all resultsFirst completed result
Use caseNeed all resultsNeed fastest result
Execution methodParallel executionParallel execution

Promise.allSettled()

Added in ES2020, waits for all Promises to complete (whether successful or failed), returns the status and result of each Promise:

javascript
Promise.allSettled([promise1, promise2, promise3]) .then(results => { results.forEach(result => { if (result.status === 'fulfilled') { console.log('Success:', result.value); } else { console.log('Failure:', result.reason); } }); });

Promise.any()

Added in ES2021, returns the first successful Promise, if all Promises fail, returns AggregateError:

javascript
Promise.any([promise1, promise2, promise3]) .then(result => console.log('First success:', result)) .catch(error => console.log('All failed:', error));

Practical Application Recommendations

  1. Use Promise.all(): When all data needs to be ready, such as loading multiple required resources
  2. Use Promise.race(): When only the fastest result is needed, such as setting timeouts or getting data from multiple mirror sources
  3. Use Promise.allSettled(): When you need to know the result of each operation, even if some fail
  4. Use Promise.any(): When only one successful result is needed, such as getting data from multiple backup servers
标签:Promise