我不明白发生了什么事......
Using q
承诺,这有效:
const deferred = q.defer();
deferred.resolve('Hellow');
const myPromise = deferred.promise;
router.get('/items', (req, res) => {
myPromise.then((result) => res.send(result));
});
但这不会,它会让浏览器保持请求永远不会结束的状态:
router.get('/items', (req, res) => {
myPromise.then(res.send);
});
怎么了?
下面是片段express
相关的图书馆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];
}
}
//.....
正如你所看到的,有很多this
参考。在你的情况下myPromise.then(res.send)
the this
指的是承诺对象,而不是res
,这就是您的代码不起作用的原因。
您可以使用以下方法更改上下文.bind https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind方法,所以this
将参考res
object:
router.get('/items', (req, res) => {
myPromise.then(res.send.bind(res));
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)