Promise.each without bluebird

三世轮回 提交于 2020-01-24 02:14:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!