Home >Web Front-end >JS Tutorial >How Can I Wait for Multiple JavaScript Promises to Finish Before Continuing?
Problem:
You have a series of asynchronous tasks (promises) and need to execute a block of code only when all of them have been completed.
Solution:
Use Promise.all to collect all promises into a single array and wait for its resolution or rejection.
Implementation:
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 });
Revised doSomeAsyncStuff function:
function doSomeAsyncStuff() { return new Promise((resolve, reject) => { const editor = generateCKEditor(); editor.on('instanceReady', (evt) => { doSomeStuff(); resolve(true); }) }); }
Example:
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((e) => { // Handle errors here }); } test();
The above is the detailed content of How Can I Wait for Multiple JavaScript Promises to Finish Before Continuing?. For more information, please follow other related articles on the PHP Chinese website!