I need using Promise.each
on bluebird. But when I see the bundle files, I'm actually thinking twice using bluebird or not.
Can anyone give me an example using function like bluebird Promise.each
without dependencies.
Sure:
Promise.each = function(arr, fn) { // take an array and a function
// invalid input
if(!Array.isArray(arr)) return Promise.reject(new Error("Non array passed to each"));
// empty case
if(arr.length === 0) return Promise.resolve();
return arr.reduce(function(prev, cur) {
return prev.then(() => fn(cur))
}, Promise.resolve());
}
Or with modern JS (Chrome or Edge or with a transpiler):
Promise.each = async function(arr, fn) { // take an array and a function
for(const item of arr) await fn(item);
}