Home > Web Front-end > JS Tutorial > How to Ensure a Callback is Executed After All Asynchronous Operations in a forEach Loop Complete?

How to Ensure a Callback is Executed After All Asynchronous Operations in a forEach Loop Complete?

Linda Hamilton
Release: 2024-11-04 14:17:02
Original
1025 people have browsed it

How to Ensure a Callback is Executed After All Asynchronous Operations in a forEach Loop Complete?

Asynchronous forEach Completion Callback

Problem:

How to execute a callback when all asynchronous operations within a forEach loop have completed?

Solution:

1. Using a Simple Counter:

Initialize a counter itemsProcessed to 0. Increment the counter in the callback of each asynchronous function. When itemsProcessed reaches the total array length, invoke the "all done" callback.

2. Using ES6 Promises:

Create an array of Promise objects representing each asynchronous operation using Promise.all. When all Promises have completed, the final callback will be executed.

3. Using an Async Library:

Utilize async libraries like async to provide mechanisms for expressing asynchronous completion callbacks.

Revised Example (Counter Method):

<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

Revised Expected Output:

3 done
1 done
2 done
All done!
Copy after login

The above is the detailed content of How to Ensure a Callback is Executed After All Asynchronous Operations in a forEach Loop 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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template