node.js - express res.send as result of promise -
i'm not understanding what's going on...
using q
promises, works:
const deferred = q.defer(); deferred.resolve('hellow'); const mypromise = deferred.promise; router.get('/items', (req, res) => { mypromise.then((result) => res.send(result)); });
but doesn't, keeps browser if request never ends:
router.get('/items', (req, res) => { mypromise.then(res.send); });
what's wrong?
below fragment of express
library related 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 can see, there lots of this
references. in case mypromise.then(res.send)
this
refers promise object, not res
, that's why code doesn't work.
you can change context using .bind method, this
refer res
object:
router.get('/items', (req, res) => { mypromise.then(res.send.bind(res)); });
Comments
Post a Comment