作为承诺的结果表示重新发送 [英] express res.send as result of promise
本文介绍了作为承诺的结果表示重新发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不明白发生了什么事...
I'm not understanding what's going on...
使用q
许诺,这行得通:
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);
});
怎么了?
推荐答案
以下是与res.send
相关的express
库的片段:
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];
}
}
//.....
如您所见,有很多this
引用.在您的情况下,myPromise.then(res.send)
this
指的是promise对象,而不是res
,这就是您的代码不起作用的原因.
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.
您可以使用 .bind 方法,因此this
将引用res
对象:
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));
});
这篇关于作为承诺的结果表示重新发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文