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)
})
}Written by Chris Turnbull
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Nodejs
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#