为什么我不能内联调用 res.json? [英] Why cant I inline call to res.json?
问题描述
我有 expressjs 应用程序,在特定的路由上,我调用了一个函数,该函数通过调用 res.json
以数据库文档作为参数来响应数据库中的用户.我使用基于 Promise 的库,并且我想内联回调,我将数据库文档放入响应中.但是当我这样做时程序会失败.有人可以解释为什么吗?我也想知道为什么对 console.log
的内联调用确实有效.res.json
和 console.log
这两种方法之间有什么根本区别吗?
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
?
这里有一个例子,说明什么有效,什么无效.假设 getUserFromDatabase()
返回用户文档的承诺.
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);
}
推荐答案
json
函数在这样使用时会失去其正确的 this
绑定,因为 .then
将直接调用它而不引用 res
父对象,因此绑定它:
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屋!