JavaScript Promises forEach with promises

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


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) {
  var i = 0;

  var nextPromise = function () {
    if (i >= arr.length) {
      // Processing finished.

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

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

This can be helpful if you need to efficiently process thousands of items, one at a time. Using a regular for loop to create the promises will create them all at once and take up a significant amount of RAM.

Got any JavaScript Question?