forEach() with promises

suggest change

It is possible to effectively apply a function (cb) which returns a promise to each element of an array, with each element waiting to be processed until the previous element is processed.

function promiseForEach(arr, cb) {
  let i = 0;

  const nextPromise = function () {
    if (i >= arr.length) {
      // Processing finished.
      return;
    }

    // Process next function. Wrap in `Promise.resolve` in case
    // the function does not return a promise
    const newPromise = Promise.resolve(cb(arr[i], i));
    i++;
    // Chain to finish processing.
    return newPromise.then(nextPromise);
  };

  // Kick off the chain.
  return Promise.resolve().then(nextPromise);
};

The next callback starts only after the previous promise settles, so the work is sequential. A loop that starts every call immediately runs the tasks concurrently instead. If cb throws, or returns a rejection, the chain rejects. An empty array resolves to undefined.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents