Control flow with promises

Promises are very powerful and allow us to create really complex asynchronous data flows.

When we want to execute tasks at the same time we can use Promise.all(), but if we want to execute tasks one after the other, we need to use a different solution.

Here is an example on how to implement a Promise.series() like method, using an array of values and the Array.reduce() function.


function addProms(n){
  return new Promise(function(resolve,reject){
    console.log("start:" + n + " on " + Date.now())
    setTimeout(function(){      
      console.log("end:" + n)
      resolve(n)
    },getRandomInt(10,5))    
  })  
}

var arr = []
for(var i=0; i<10; i++){ arr.push(i) } function getrandomint(min, max) { return math.floor(math.random() * (max - min)) + min console.log('###########################') console.log("start parallel") var proms="arr.map(function(it){" addproms(it) }) promise.all(proms).then(function(res){ console.log("finished settimeout(function(){ console.log('start series') data="[];" arr.reduce(function(acc,it){ acc.then(function(){ }, promise.resolve()) .then(function(v){ series") },500) each') arr.foreach(function(i){ addproms(i).then(function(i){ return; console.log('end },1000) < code>