Aral Roca Aral Roca - 20 days ago 6
Javascript Question

Node.js: Response inside a promise

Anybody can me explain why this:

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


Is not equivalent to:

somePromise()
.then(res.status(200).jsonp)
.catch(res.status(500).send);


The first code is working well, the second not

Answer

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:

somePromise()
    .then(res.status(200).jsonp.bind(res))
    .catch(res.status(500).send.bind(res));

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