Home > Article > Web Front-end > How to Ensure a Callback is Executed After All Asynchronous Operations in a forEach Loop Complete?
Problem:
How to execute a callback when all asynchronous operations within a forEach loop have completed?
Solution:
1. Using a Simple Counter:
Initialize a counter itemsProcessed to 0. Increment the counter in the callback of each asynchronous function. When itemsProcessed reaches the total array length, invoke the "all done" callback.
2. Using ES6 Promises:
Create an array of Promise objects representing each asynchronous operation using Promise.all. When all Promises have completed, the final callback will be executed.
3. Using an Async Library:
Utilize async libraries like async to provide mechanisms for expressing asynchronous completion callbacks.
Revised Example (Counter Method):
<code class="javascript">function callback() { console.log("All done!"); } var itemsProcessed = 0; [1, 2, 3].forEach((item, index, array) => { asyncFunction(item, () => { itemsProcessed++; if (itemsProcessed === array.length) { callback(); } }); });</code>
Revised Expected Output:
3 done 1 done 2 done All done!
The above is the detailed content of How to Ensure a Callback is Executed After All Asynchronous Operations in a forEach Loop Complete?. For more information, please follow other related articles on the PHP Chinese website!