Home > Web Front-end > JS Tutorial > How Can I Run Multiple Async Operations Concurrently in JavaScript?

How Can I Run Multiple Async Operations Concurrently in JavaScript?

Patricia Arquette
Release: 2024-12-07 22:41:17
Original
1001 people have browsed it

How Can I Run Multiple Async Operations Concurrently in JavaScript?

Concurrent Execution of Multiple Async Operations

Problem:

In the code below, the async operations are executed sequentially, not concurrently:

const value1 = await getValue1Async();
const value2 = await getValue2Async();
Copy after login

To run the operations concurrently, we need to modify the code.

Solution:

TL;DR

Use Promise.all instead of the sequential await pattern:

const [value1, value2] = await Promise.all([getValue1Async(), getValue2Async()]);
Copy after login

Details:

The original solution runs the two operations in parallel but waits for the first to complete before waiting for the second. This can lead to performance issues if one operation takes significantly longer than the other.

Promise.all allows us to wait for multiple operations to complete concurrently. It takes an array of promises and returns a promise that resolves to an array of the results in the same order as the original array.

Advantages of Promise.all:

  • Concurrent execution of operations
  • Handles rejection properly if any of the promises reject
  • More concise code

Caution:

Note that if the second promise rejects before the first promise resolves, the "get the promise then await it" pattern may result in an "unhandled rejection" error. This can be avoided by using Promise.all.

Example:

Here's a revised example using Promise.all:

const getValue1Async = () => {
  return new Promise(resolve => {
    setTimeout(resolve, 500, "value1");
  });
};

const getValue2Async = () => {
  return new Promise((resolve, reject) => {
    setTimeout(reject, 100, "error");
  });
};

(async () => {
  try {
    console.time("Promise.all");
    const [value1, value2] = await Promise.all([getValue1Async(), getValue2Async()]);
  } catch (e) {
    console.timeEnd("Promise.all", e);
  }
})();
Copy after login

This code shows how Promise.all enables concurrent execution of the two async operations, resulting in faster completion.

The above is the detailed content of How Can I Run Multiple Async Operations Concurrently in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template