Iterate an array with a promise in javascript

Example of how to iterate an array with a promise

It can be challenging to figure out how to iterate over an array of items with a promise.

The following code takes a callback function that may or may not be a promise already.

Once inside the PromiseForEach function, the callback will become a promise (if it isn’t already).

You also have the option of pushing the values onto an output array,  responseArray in the example below.

The response from the callback may be pushed directly onto the responseArray resulting in an array of promises that may be further manipulated, although at this point I am not sure why one would do that.


// Function to iterate an array with promises
  // Array to be iterated
  var someArray = [foo, bar, baz];
  // some callback function (may or maynot be a promise)
  // however it will ultimately become a promise once
  // inside PromisesForEach(arr, callback )
  function processSomeArray(someArray){
      //  do stuff here ...
      //  return some value 

  called like this: PromisesForEach(someArray, processSomeArray )

   each element in the array (may be an object) is passed as a 
   paramiter to the callback function.

   the callback may be a `.thenable` promise but 
   doesn't have to with this setup

   Each callback function is ultimately called as a promise
   by this function.

function PromisesForEach(arr, callback ) {
  var i = 0, response, mappedData, responseArray = [];

  // Kick off the chain.
  // This is an 'immediately resolved promise' (google it)
  // the 'new' constructor is not needed.
  //    returns a Promise object that is resolved with the given value.
  // The static Promise.resolve function returns a Promise that is resolved.
  return Promise.resolve().then(nextPromise);

  //nextPromise = function()
  var nextPromise = function(){
       // Exit when array has been exhausted
       if ( i >= arr.length ) {
           // Possibly do something here or
           // Possibly return an array of:
           //    objects, strings or whatever
           //    promises for further processing
           return responseArray ;
       // If not exited then
       // Process next function. Wrap in `Promise.resolve` in case
       // the function does not return a promise
       // This is an 'immediately resolved promise' (google it)
       var newPromise = Promise.resolve( callback( arr[i], i) );
          // This is the result of the callback.
          someresult = doSomethingWith(resolveFromCallback);
          // May concatinate a string value    or
          // response += someresult + "\n";
          //build an array of someresult s
          responseArray.push(someresult) ;

        // Chain to finish processing.
        return newPromise.then(nextPromise);
    };//nextPromise = function()


Leave a Reply

Your email address will not be published. Required fields are marked *