问题
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.
回答1:
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);
}
回答2:
If we look at the Promise
documentation on MDN, you can see there's two methods we would be able to use. all
and race
, the former finishes when all promises are resolved where the latter finishes when the first promise resolves.
This should give you the tools to do everything you could do with bluebirds Promise.each
. If it doesn't solve your problem yet, please state your concrete problem and I'll see if I can help you out.
来源:https://stackoverflow.com/questions/41607804/promise-each-without-bluebird