Lud*_*son 13 javascript node.js promise express
我有和表达应用程序,并在特定的路径上,我调用一个函数,通过调用res.json
数据库文档作为参数,从数据库响应用户.我使用基于promise的库,我想内联回调,我将数据库文档放在响应中.但是当我这样做时,程序失败了.有人可以解释一下原因吗?我也想知道为什么内联电话要console.log
实际工作.有两种方法之间的一些根本的区别res.json
和console.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);
}
Run Code Online (Sandbox Code Playgroud)
Pet*_*ons 12
该json
函数this
在使用时失去了正确的绑定,因为.then
它将直接调用它而不引用res
父对象,因此绑定它:
var getUserInline = function(req, res) {
getUserFromDatabase().then(res.json.bind(res));
}
Run Code Online (Sandbox Code Playgroud)