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)
—Read This Next—

Camera tracking with NodeJS and Arduino


Lately I had some fun using the Arduino micro-controller with NodeJS. One of my last project is a camera mounted on a Pan&Tilt that can
—You Might Enjoy—

Wemos D1 Mini Pinout


The Wemos D1 mini is a really cool microcontroller. It costs only £5 and provides integrated WiFi bng connectivity and 13 digital I/O and 1