Skip to content

Instantly share code, notes, and snippets.

@ritch
Created September 13, 2011 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ritch/1213259 to your computer and use it in GitHub Desktop.
Save ritch/1213259 to your computer and use it in GitHub Desktop.
Async via EventEmitter
// 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
});
// 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