Executing Async Functions in Parallel
In ES7/ES2016, sequential execution of await expressions is the default behavior, akin to chaining promises with .then(). However, to perform asynchronous calls in parallel, there are alternative approaches.
Parallel Execution with Promise.all()
One elegant solution is to use Promise.all(). This method takes an array of promises and returns a single promise that resolves to an array of results:
await Promise.all([someCall(), anotherCall()]);
To store the individual results, you can destructure the return value into variables:
let [someResult, anotherResult] = await Promise.all([someCall(), anotherCall()]);
Caveat: Handle Rejections with catch()
Note that Promise.all() implements "fail fast" semantics. This means if any one of the input promises rejects, the entire operation will reject with the error from the failed promise. To catch and handle potential errors, use the .catch() method.
For example:
Promise.all([happy('happy', 100), sad('sad', 50)]) .then(console.log).catch(console.log); // Logs 'sad'
The above is the detailed content of How Can I Execute Async Functions in Parallel in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!