forEach() with promises
suggest changeIt 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents