Home > Web Front-end > JS Tutorial > How to Execute a Callback after Asynchronous forEach Tasks Complete?

How to Execute a Callback after Asynchronous forEach Tasks Complete?

Mary-Kate Olsen
Release: 2024-11-04 12:53:01
Original
357 people have browsed it

How to Execute a Callback after Asynchronous forEach Tasks Complete?

Executing a Callback after Asynchronous forEach Tasks are 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.

Using a Counter

<br>function callback() { console.log('all done'); }</p>
<p>var itemsProcessed = 0;</p>
<p>[1, 2, 3].forEach(item => {<br>  asyncFunction(item, () => {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">itemsProcessed++;
if(itemsProcessed === array.length) {
  callback();
}
Copy after login

});
});

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.

Using ES6 Promises

  • Synchronous Execution:
    <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.

    • Asynchronous Execution:
      <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.

      Using an Async Library

      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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template