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

我有和expressjs应用程序,并在特定的路线我调用一个函数,通过调用res.json与数据库文件作为参数与数据库中的用户响应。 我使用基于承诺的库,我想内联的callback,我把数据库文件的响应。 但是当我这样做的时候程序就会失败。 有人可以解释为什么吗? 我也想知道为什么内联调用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函数在使用时会失去正确的绑定,因为直接调用它而不参考res父对象,所以绑定它:

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