问题
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?
回答1:
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));
});
来源:https://stackoverflow.com/questions/38187342/express-res-send-as-result-of-promise