无蓝鸟的承诺

问题描述:

我需要在 bluebird 上使用Promise.each.但是,当我看到捆绑文件时,实际上我是否在考虑是否使用 bluebird .

I need using Promise.each on bluebird. But when I see the bundle files, I'm actually thinking twice using bluebird or not.

任何人都可以使用没有依赖项的 bluebird Promise.each之类的函数给我一个例子.

Can anyone give me an example using function like bluebird Promise.each without dependencies.

确定:

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());
}

或者使用现代JS(Chrome或Edge或带有Transpiler):

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);
}