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.
return;
}
// Process next function. Wrap in `Promise.resolve` in case
// the function does not return a promise
var 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);
};
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.