Home >Web Front-end >JS Tutorial >How to Execute a Callback after Asynchronous forEach Tasks Complete?
Problem
How can we execute a callback function once all asynchronous operations within a forEach loop have been completed?
Answer
Array.forEach does not provide an out-of-the-box solution for this scenario, but there are various approaches to achieve the desired functionality.
<br>function callback() { console.log('all done'); }</p> <p>var itemsProcessed = 0;</p> <p>[1, 2, 3].forEach(item => {<br> asyncFunction(item, () => {</p> <pre class="brush:php;toolbar:false">itemsProcessed++; if(itemsProcessed === array.length) { callback(); }
});
});
This approach uses a counter that is incremented each time an asynchronous operation is completed. Once the counter reaches the total number of items in the array, the callback function is invoked.
<br>const requests = [1, 2, 3].reduce((promiseChain, item) => {<br>return promiseChain.then(() => new Promise((resolve) => {<br> asyncFunction(item, resolve);<br>}));<br>}, Promise.resolve());</li></ul> <p>requests.then(() => console.log('done'))<br>
In this example, we chain promises to guarantee that each asynchronous operation completes before the next one starts.
<br>const requests = [1,2,3].map((item) => {<br>return new Promise((resolve) => {<br> asyncFunction(item, resolve);<br>});<br>})</li></ul> <p>Promise.all(requests).then(() => console.log('done'));<br>
In this case, we use the Promise.all method to execute all asynchronous operations simultaneously and then invoke the callback when all of them are completed.
Asynchronous libraries like async provide mechanisms to express the desired functionality more elegantly.
The above is the detailed content of How to Execute a Callback after Asynchronous forEach Tasks Complete?. For more information, please follow other related articles on the PHP Chinese website!