Last Updated: February 25, 2016
·
668
· christurnbull

Node.js: Iterate over Async Function with For Loop & Events

Sometimes you just want to call an async function a bunch of times then do something when all the callbacks are complete.
Here's how it can be done using the familiar syntax of a For Loop and Events

Require events and create a wrapper function to keep a track on the counter

var events = require('events')
var eventEmitter = new events.EventEmitter()
function loopWrap(counter,cb){cb(counter)}

Do stuff when all callbacks are complete

function loopA(){
    //do stuff...
    console.log('loopA done')
}
eventEmitter.on('loopA', loopA)

Stick the async function in a (synchronous) For Loop & emit 'done' Event on last loop

var dataArr = [1,2,3,4,5]
for(var i=0; i<dataArr.length; i++){ loopWrap(i,function(j){
    setTimeout(function(){  // setTimeout used as example. Could be any func
      console.log(j)  // do stuff...

      if(j==dataArr.length-1)  eventEmitter.emit('loopA')
    }, 1000)
  })
}