Home  >  Article  >  Web Front-end  >  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
Linda HamiltonOriginal
2024-11-04 14:17:02985browse

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>

Revised Expected Output:

3 done
1 done
2 done
All done!

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!

Statement:
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