Home > Web Front-end > JS Tutorial > How to Implement a Completion Callback for Asynchronous forEach Loops?

How to Implement a Completion Callback for Asynchronous forEach Loops?

DDD
Release: 2024-11-04 13:09:01
Original
708 people have browsed it

How to Implement a Completion Callback for Asynchronous forEach Loops?

Asynchronous forEach Callbacks: Implementing a Completion Callback

In scenarios where an asynchronous loop like forEach is employed, the need often arises to trigger a callback once all asynchronous operations have completed. This guide presents several approaches to achieve this functionality.

1. Utilizing a Simple Counter

This technique employs a counter that increments every time an item is processed. When the counter reaches the total number of items, the completion callback is invoked.

function callback () { console.log('all done'); }

var itemsProcessed = 0;

[1, 2, 3].forEach((item, index, array) => {
  asyncFunction(item, () => {
    itemsProcessed++;
    if(itemsProcessed === array.length) {
      callback();
    }
  });
});
Copy after login

2. Leveraging ES6 Promises

Promises enable the creation of a sequential promise chain, ensuring synchronous execution of asynchronous tasks.

function asyncFunction (item, cb) {
  setTimeout(() => {
    console.log('done with', item);
    cb();
  }, 100);
}

let requests = [1, 2, 3].reduce((promiseChain, item) => {
    return promiseChain.then(() => new Promise((resolve) => {
      asyncFunction(item, resolve);
    }));
}, Promise.resolve());

requests.then(() => console.log('done'))
Copy after login

3. Employing an Asynchronous Library

Libraries like "async" provide mechanisms for expressing the desired functionality. The specific implementation will vary depending on the library chosen.

The above is the detailed content of How to Implement a Completion Callback for Asynchronous forEach Loops?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template