最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why cant I inline call to res.json? - Stack Overflow

programmeradmin0浏览0评论

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

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);    
} 
Share Improve this question edited Feb 6, 2015 at 13:16 Bergi 666k161 gold badges1k silver badges1.5k bronze badges asked Aug 2, 2013 at 10:13 Ludwig MagnussonLudwig Magnusson 14.4k10 gold badges40 silver badges54 bronze badges 1
  • It looks like a binding problem. alistapart./article/getoutbindingsituations – randunel Commented Aug 2, 2013 at 10:29
Add a ment  | 

1 Answer 1

Reset to default 12

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));    
}
发布评论

评论列表(0)

  1. 暂无评论