Home > Web Front-end > JS Tutorial > How to Execute a Callback Function After Asynchronous Processing within a ForEach Loop?

How to Execute a Callback Function After Asynchronous Processing within a ForEach Loop?

Susan Sarandon
Release: 2024-11-04 15:10:02
Original
279 people have browsed it

How to Execute a Callback Function After Asynchronous Processing within a ForEach Loop?

Callback Completion After Asynchronous Iterative Processing

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

  • Increment a counter within each asynchronous callback.
  • Execute the "done" callback when the counter reaches the total number of elements.
<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>
Copy after login

Solution 2: Promise-Based Approach

Synchronous Execution:

  • Chain promises using reduce() and Promise.resolve() to guarantee 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>
Copy after login

Asynchronous Execution:

  • Create an array of promises using map().
  • Use Promise.all() to invoke the "done" callback when all promises have resolved.
<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>
Copy after login

Solution 3: Async Library Usage

  • Leverage libraries like async to simplify asynchronous programming patterns.
  • Refer to specific documentation for callback completion mechanisms provided by the library.

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!

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template