express res.send as result of promise

走远了吗. 提交于 2020-01-03 10:06:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!