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
javascriptconst 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
- Parallel execution: All Promises start executing simultaneously
- Order guarantee: Result array order matches input order
- Fast fail: If any fails, the entire operation fails immediately
- 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
- Fast return: Returns the first completed result
- State inheritance: Success or failure depends on the first completed Promise
- Uncertainty: Which Promise completes first is uncertain
- Empty array: If an empty array is passed, the Promise remains in pending state forever
Comparison Summary
| Feature | Promise.all() | Promise.race() |
|---|---|---|
| Completion condition | All Promises succeed | First Promise completes |
| Failure condition | Any Promise fails | First Promise fails |
| Return result | Array of all results | First completed result |
| Use case | Need all results | Need fastest result |
| Execution method | Parallel execution | Parallel execution |
Other Related Methods
Promise.allSettled()
Added in ES2020, waits for all Promises to complete (whether successful or failed), returns the status and result of each Promise:
javascriptPromise.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:
javascriptPromise.any([promise1, promise2, promise3]) .then(result => console.log('First success:', result)) .catch(error => console.log('All failed:', error));
Practical Application Recommendations
- Use Promise.all(): When all data needs to be ready, such as loading multiple required resources
- Use Promise.race(): When only the fastest result is needed, such as setting timeouts or getting data from multiple mirror sources
- Use Promise.allSettled(): When you need to know the result of each operation, even if some fail
- Use Promise.any(): When only one successful result is needed, such as getting data from multiple backup servers