760900
原文链接如下: http://www.infoq.com/cn/articles/tyq-nodejs-event,作者为淘宝的朴灵,原名田永强
其中提到了通过将请求的回调函数压入事件队列中来解决雪崩的办法,核心代码如下:
var proxy = new EventProxy();
var status = "ready";
var select = function (callback) {
proxy.once("selected", callback);
if (status === "ready") {
status = "pending";
db.select("SQL", function (results) {
proxy.emit("selected", results);
status = "ready";
});
}
};
由于没找到完整代码,我便创建了一个http server来验证,验证结果确实是db查询的次数大大减少,补全后的核心代码如下:
var _db,
status = 'ready',
event = new emitter();
event.setMaxListeners(0);
mongodb.open(function(err, db) {
_db = db;
});
http.createServer(function(request, response) {
event.once('got', function(result) {
response.writeHead(200);
response.end(result.name);
});
if (status == 'ready') {
status = "pendding";
_db.collection('users', function(err, collection) {
collection.findOne({name: 'leo'}, function(err, doc) {
doc && event.emit('got', doc);
status = "ready";
});
});
}
}).listen(9090);
我现在的问题就是我的代码这样写对吗?请高人指点一二。