Home  >  Article  >  Web Front-end  >  How Can I Execute Async Functions in Parallel in JavaScript?

How Can I Execute Async Functions in Parallel in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-24 03:35:10378browse

How Can I Execute Async Functions in Parallel in JavaScript?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn