If you need to access all the Promises results (like you can with Promise.all) - you can do the following:
Promise.series = (array, fn, thisArg) => {
var p = Promise.resolve();
return Promise.all(Array.from(array).map((...args) =>
p = p
.then(() => fn.apply(thisArg, args))
));
};
Then your code becomes
const arrayABC = [a, b, c.....x, y, z] // length unknown
return Promise.series(promises, doSomething);
The callback (in this case doSomething
) will be passed the arguments item, index, array
, just like Array#map
, Array#forEach
etc
thisArg
is optional, and works just like how you would use it for Array#map
, Array#forEach
etc
An alternative Promise.series
Promise.series = (array, fn, thisArg) =>
Array.from(array).reduce((promise, ...args) =>
promise
.then(results =>
fn.apply(thisArg, args)
.then(result => results.concat(result))
), Promise.resolve([])
);
same result, but no need for Promise.all