I'm not understanding what's going on...
Using q
promises, this works:
const deferred = q.defer();
deferred.resolve('Hellow');
const myPromise = deferred.promise;
router.get('/items', (req, res) => {
myPromise.then((result) => res.send(result));
});
but this doesn't, it keeps the browser like if the request never ends:
router.get('/items', (req, res) => {
myPromise.then(res.send);
});
What's wrong?
res is the flag. The code within that then handler calls another function, setLikeCanceled , which also returns a promise. The then handler on that promise is written to use res as the parameter name. This is a different parameter than the first one, containing the fulfillment value from setLikeCanceled .
The res. send function sets the content type to text/Html which means that the client will now treat it as text. It then returns the response to the client.
res. send() is used to send the response to the client where res. end() is used to end the response you are sending.
Express doesn't support promises or async/await in middleware or routes. In the below example, the Express endpoint will never send a response because of an unhandled promise rejection.
Below is the fragment of the express
library related to res.send
:
res.send = function send(body) {
var chunk = body;
var encoding;
var len;
var req = this.req;
var type;
// settings
var app = this.app;
// allow status / body
if (arguments.length === 2) {
// res.send(body, status) backwards compat
if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {
deprecate('res.send(body, status): Use res.status(status).send(body) instead');
this.statusCode = arguments[1];
} else {
deprecate('res.send(status, body): Use res.status(status).send(body) instead');
this.statusCode = arguments[0];
chunk = arguments[1];
}
}
//.....
As you can see, there are lots of this
references. In your case myPromise.then(res.send)
the this
refers to promise object, not to res
, that's why your code doesn't work.
You can change the context by using .bind method, so this
will refer to res
object:
router.get('/items', (req, res) => {
myPromise.then(res.send.bind(res));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With