Promise.each without bluebird

Rohman Masyhar picture Rohman Masyhar · Jan 12, 2017 · Viewed 9.3k times · Source

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.

Answer

Benjamin Gruenbaum picture Benjamin Gruenbaum · Jan 12, 2017

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