为什么我不能内联调用res.json

Why cant I inline call to res.json?

本文关键字:调用 res json 不能 为什么      更新时间:2023-09-26

我有一个expressjs应用程序,在特定的路由上,我调用一个函数,该函数通过以数据库文档为参数调用res.json来响应数据库中的用户。我使用基于promise的库,并且我想在响应中放入数据库文档的地方内联回调。但是当我这么做的时候程序失败了。有人能解释一下为什么吗?我还想知道为什么对console.log的内联调用确实有效。res.jsonconsole.log这两种方法之间有什么根本的区别吗?

下面是一个什么有效,什么无效的例子。假设getUserFromDatabase()返回一个用户文档的承诺。

//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);    
} 

json函数在这样使用时会丢失其正确的this绑定,因为.then将直接调用它,而不引用res父对象,所以绑定它:

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