Created
October 5, 2012 14:13
-
-
Save rehanift/3840004 to your computer and use it in GitHub Desktop.
Mixing callbacks with events
This file contains 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
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