为什么不能内联来调用res.json? [英] Why cant I inline call to res.json?
问题描述
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屋!