我有一个简单的函数,用于路由HTTP查询模式,查询redis并发送响应。以下是代码
router.get('/getinfo/:teamname', function main(teamname) {
rclient.hgetall(teamname,function(err,obj){
console.log("the response from redis is ",obj)
cache.put(eventname,obj);
console.log("inserting to cache");
this.res.end(obj); // this object is root cause for all problems
});
}
路由器对象afaik,使用this.res.end(obj)
发送响应。我想因为我试图在我的redis客户端中执行此操作,所以我收到错误。有没有其他方法可以将值作为响应发送?我想过使用基于发射器的模型,其中通道发出响应并且侦听器获取它。但这感觉就像解决这个问题的方法。有没有更简单的方法?
答案 0 :(得分:1)
错误可能是因为,在您尝试使用this
时,它没有预期的值 - 具有res
属性的对象又具有{{1方法。
这是因为JavaScript中的每个end()
都有自己的function
,并且有自己的值。并且,在嵌套this
时,使用function
将返回最接近this
的值(即shadowing)。
要解决此问题,您可以将预期值保存到本地变量:
function
或者bind
匿名回调,因此两个router.get('/getinfo/:teamname', function main(teamname) {
var request = this;
rclient.hgetall(teamname,function(err,obj){
// ...
request.res.end(obj);
});
});
被强制拥有相同的function
值:
this