Asynchronous forEach Callbacks: Implementing a Completion Callback
In scenarios where an asynchronous loop like forEach is employed, the need often arises to trigger a callback once all asynchronous operations have completed. This guide presents several approaches to achieve this functionality.
1. Utilizing a Simple Counter
This technique employs a counter that increments every time an item is processed. When the counter reaches the total number of items, the completion callback is invoked.
function callback () { console.log('all done'); } var itemsProcessed = 0; [1, 2, 3].forEach((item, index, array) => { asyncFunction(item, () => { itemsProcessed++; if(itemsProcessed === array.length) { callback(); } }); });
2. Leveraging ES6 Promises
Promises enable the creation of a sequential promise chain, ensuring synchronous execution of asynchronous tasks.
function asyncFunction (item, cb) { setTimeout(() => { console.log('done with', item); cb(); }, 100); } let requests = [1, 2, 3].reduce((promiseChain, item) => { return promiseChain.then(() => new Promise((resolve) => { asyncFunction(item, resolve); })); }, Promise.resolve()); requests.then(() => console.log('done'))
3. Employing an Asynchronous Library
Libraries like "async" provide mechanisms for expressing the desired functionality. The specific implementation will vary depending on the library chosen.
The above is the detailed content of How to Implement a Completion Callback for Asynchronous forEach Loops?. For more information, please follow other related articles on the PHP Chinese website!