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")  
console.log('###########################')
var proms = arr.map(function(it){
  return addProms(it)
})
Promise.all(proms).then(function(res){
  console.log('###########################')
  console.log("finished parallel")    
  console.log('###########################')
})

setTimeout(function(){
  console.log('###########################')
  console.log('start series')
  console.log('###########################')

  var data = [];
  arr.reduce(function(acc,it){  
    return acc.then(function(){    
      return addProms(it)
    })

  }, Promise.resolve())
    .then(function(v){
     console.log('###########################')
     console.log("finished series")   
     console.log('###########################')
  })
},500)

setTimeout(function(){
  console.log('###########################')
  console.log('start each')
  console.log('###########################')
arr.forEach(function(i){
  return addProms(i).then(function(i){
    return;
  })
})

console.log('###########################')
  console.log('end each')
  console.log('###########################')

},1000)

Davide Andreazzini

Read more posts by this author.