为什么不能内联来调用res.json? [英] Why cant I inline call to res.json?

查看:98
本文介绍了为什么不能内联来调用res.json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有和expressjs应用程序,在特定的路由我调用一个函数,用数据库文件作为参数调用 res.json 从数据库中回应用户。我使用基于promise的库,我想内联回调,我将数据库文档放在响应中。但是当我这样做时,程序失败。有人可以解释为什么吗?我也想知道为什么内联调用 console.log 实际上可以工作。两种方法 res.json console.log 之间有一些根本区别?



这是一个有用的例子,什么不起作用。假设 getUserFromDatabase()返回用户文档的承诺。

  /这个工程
var getUser = function(req,res){
getUserFromDatabase()。then(function(doc){
res.json(doc);
});
}

//这不起作用(服务器从不响应请求)
var getUserInline = function(req,res){
getUserFromDatabase()。然后(res.json);
}

//这个工作(对象被打印到控制台)
var printUser = function(req,res){
getUserFromDatabase()的console.log);
}


解决方案

json 函数失去正确的这个绑定,因为 .then 正在进行直接调用它而不引用 res 父对象,所以绑定它:

  var getUserInline = function(req,res){
getUserFromDatabase()。then(res.json.bind(res));
}


I have and expressjs application and on a specific route I call a function that responds with a user from the database by calling res.json with the database document as parameter. I use promise based libraries and I wanted to inline the callback where I am putting the database document in the response. But the program fails when I do so. Can somebody explain why? I also wonder why inlined calls to console.log actually do work. Is there some fundamental difference between the two methods res.json and console.log?

Here is an example of what works and what does not work. Assume getUserFromDatabase() returns a promise of a user document.

//This works
var getUser = function(req, res) {
    getUserFromDatabase().then(function(doc) {
        res.json(doc);
    });    
} 

//This does not work (the server never responds to the request)
var getUserInline = function(req, res) {
    getUserFromDatabase().then(res.json);    
} 

//This works (the object is printed to the console)
var printUser = function(req, res) {
    getUserFromDatabase().then(console.log);    
} 

解决方案

The json function loses its correct this binding when used like that since .then is going to invoke it directly without reference to the res parent object, so bind it:

var getUserInline = function(req, res) {
    getUserFromDatabase().then(res.json.bind(res));    
}

这篇关于为什么不能内联来调用res.json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆