Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cant I inline call to res.json?

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);    
} 
like image 371
Ludwig Magnusson Avatar asked Aug 02 '13 10:08

Ludwig Magnusson


People also ask

Should I use Res send or RES json?

There is no actual difference between res. send and res. json, both methods are almost identical.

Does Res json () Send?

json() Function. The res. json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.

What does Res send () do?

send() Send a string response in a format other than JSON (XML, CSV, plain text, etc.). This method is used in the underlying implementation of most of the other terminal response methods.

What content type is sent in the HTTP response when Res json () produces the response?

The res. json function on the other handsets the content-type header to application/JSON so that the client treats the response string as a valid JSON object. It also then returns the response to the client.


1 Answers

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));    
}
like image 197
Peter Lyons Avatar answered Sep 30 '22 09:09

Peter Lyons