Home >Web Front-end >JS Tutorial >How to Execute a Callback Function After Asynchronous Processing within a ForEach Loop?
Problem Statement:
Given an array of elements, how can we invoke a callback function after all asynchronous processing within a forEach loop has completed?
Solution 1: Counter-Based Approach
<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>
Solution 2: Promise-Based Approach
Synchronous Execution:
<code class="javascript">let requests = [1, 2, 3].reduce((promiseChain, item) => { return promiseChain.then(() => new Promise((resolve) => { asyncFunction(item, resolve); })); }, Promise.resolve()); requests.then(() => console.log('done'));</code>
Asynchronous Execution:
<code class="javascript">let requests = [1, 2, 3].map((item) => { return new Promise((resolve) => { asyncFunction(item, resolve); }); }); Promise.all(requests).then(() => console.log('done'));</code>
Solution 3: Async Library Usage
The above is the detailed content of How to Execute a Callback Function After Asynchronous Processing within a ForEach Loop?. For more information, please follow other related articles on the PHP Chinese website!