Aral Roca Aral Roca - 4 months ago 38
Javascript Question

Node.js: Response inside a promise

Anybody can me explain why this:

.then(content => res.status(200).jsonp(content))
.catch(err => res.status(500).send(err));

Is not equivalent to:


The first code is working well, the second not


In the first example, .jsonp and .send are invoked as methods on the res object. This is necessary in order for them to work correctly; they must have access to the response object.

In the second example, you pass a reference to the .jsonp and .send functions, but when they are invoked they are not invoked as methods on res. This means that they do not have access to the response object, causing them to fail.

UPDATE: Earlier, I had said you could modify the second example to use .bind and it should work:


That is not correct. What happens if you do the above is that the response will always have a 500 status code. That is because the execution goes like this:

  • set res.status to 200
  • bind res to .jsonp
  • set res.status to 500.
  • bind res to .send
  • Later: invoke .jsonp or .send. Both are bound to res, which has had its status code set to 500