Return Multiple Promises and Pause Execution Until All Completed
You need to handle multiple asynchronous operations with a method that returns promises. After these operations complete, you want to execute another set of code only when all promises have resolved.
Promises in doSomeAsyncStuff()
Your doSomeAsyncStuff() function needs to return a Promise. This promise reflects the completion of the asynchronous task:
function doSomeAsyncStuff() { return new Promise((resolve, reject) => { var editor = generateCKEditor(); editor.on('instanceReady', () => { doSomeStuff(); resolve(true); }); }); }
Using Promise.all()
Once your asynchronous function returns a Promise, you can use Promise.all() to aggregate these promises into a single Promise:
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((error) => { // Handle errors here });
Example
Below is an example that logs a message after all five asynchronous tasks have finished:
function doSomethingAsync(value) { return new Promise((resolve) => { setTimeout(() => { console.log("Resolving " + value); resolve(value); }, Math.floor(Math.random() * 1000)); }); } function test() { const promises = []; for (let i = 0; i < 5; i++) { promises.push(doSomethingAsync(i)); } Promise.all(promises) .then((results) => { console.log("All done", results); }) .catch((error) => { // Handle errors here }); } test();
The above is the detailed content of How to Pause Execution Until Multiple Promises Resolve?. For more information, please follow other related articles on the PHP Chinese website!