How to Handle Multiple Promises and Await Their Completion
When working with asynchronous code, it's often necessary to handle multiple promises and wait for them all to complete before proceeding. This article will guide you through achieving this using Promise.all.
Introducing Promise.all
Promise.all accepts an array of promises and returns a single promise that resolves when all the input promises have resolved, or rejects if any one of them rejects.
Restructuring doSomeAsyncStuff to Return a Promise
To make doSomeAsyncStuff work with promises, modify it as follows:
function doSomeAsyncStuff() { return new Promise((resolve) => { editor.on('instanceReady', function(evt) { doSomeStuff(); resolve(true); }); }); }
Using Promise.all to Wait for All Async Tasks
Once doSomeAsyncStuff returns a promise, you can use Promise.all to wait for all instances of it to complete. Here's an improved version of your code:
const promises = []; for (let i = 0; i < 5; i++) { promises.push(doSomeAsyncStuff()); } Promise.all(promises) .then(() => { for (let i = 0; i < 5; i++) { doSomeStuffOnlyWhenTheAsyncStuffIsFinish(); } }) .catch((e) => { // Handle errors here });
This code creates an array of promises from each call to doSomeAsyncStuff. Promise.all takes this array and waits for all the promises to resolve. Once all promises are resolved, the then callback is executed, allowing you to perform actions that depend on the results of the asynchronous tasks.
The above is the detailed content of How to Use Promise.all to Manage and Await Multiple Promises?. For more information, please follow other related articles on the PHP Chinese website!