Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express res.send as result of promise

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?

like image 660
Miquel Avatar asked Jul 04 '16 14:07

Miquel


People also ask

What is RES in promise?

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 .

What does Res send () do?

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.

What is the difference between RES end and Res send?

res. send() is used to send the response to the client where res. end() is used to end the response you are sending.

Does Express use promises?

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.


1 Answers

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));
});
like image 94
Engineer Avatar answered Sep 20 '22 12:09

Engineer