Skip to content

Instantly share code, notes, and snippets.

@rehanift
Created October 5, 2012 14:13
Show Gist options
  • Save rehanift/3840004 to your computer and use it in GitHub Desktop.
Save rehanift/3840004 to your computer and use it in GitHub Desktop.
Mixing callbacks with events
var util = require("util");
var events = require("events");
var AsyncServer = function(){
this.request_count = 0;
};
util.inherits(AsyncServer, events.EventEmitter);
AsyncServer.make = function(){
var server = new AsyncServer();
return server;
};
AsyncServer.create = function(){
var server = AsyncServer.make({});
return server;
};
AsyncServer.prototype.request = function(value, cb){
var self = this;
if (this.request_count == 0) {
this.request_count++;
process.nextTick(function(){
setTimeout(function(){
cb(value);
},1000);
});
} else {
process.nextTick(function(){
cb(value);
});
}
};
var my_server = AsyncServer.create();
my_server.request("foo", function(value){
console.log("foo is", value);
});
my_server.request("bar", function(value){
console.log("bar is", value);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment