Created
September 13, 2011 06:32
-
-
Save ritch/1213259 to your computer and use it in GitHub Desktop.
Async via EventEmitter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// parallel | |
// 3 requests happen in parallel | |
var urls = ['google.com', 'yahoo.com'] | |
, emitter = new EventEmitter() | |
, done = [] | |
; | |
function increment(res) { | |
done.push(res); | |
if(done.length === urls.length) { | |
emitter.emit('done'); | |
} | |
} | |
urls.forEach(function(url) { | |
req.get(url, increment); | |
}); | |
emitter.on('done', function() { | |
// do something will all responses | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// serial | |
// 3 requests happen in order | |
var urls = ['google.com', 'yahoo.com'] | |
, emitter = new EventEmitter() | |
, done = [] | |
; | |
function increment(res) { | |
done.push(res); | |
if(done.length < urls) { | |
emitter.emit('continue'); | |
} else { | |
emitter.emit('done'); | |
} | |
} | |
emitter.on('continue', function() { | |
req.get(urls[done.length], increment); | |
}); | |
emitter.on('done', function() { | |
// do something will all responses | |
}); | |
// start | |
emitter.emit('continue'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment