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();
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()]);
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:
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); } })();
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!