Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise.each without bluebird

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.

like image 387
Rohman HM Avatar asked Jan 12 '17 07:01

Rohman HM


1 Answers

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);
}
like image 192
Benjamin Gruenbaum Avatar answered Sep 22 '22 14:09

Benjamin Gruenbaum