Express Framework and Promises - what to return from a route handler?

I am using the following promise based pattern for my Express route handlers:

app.get('/accounts/:id', function(req, res) {

    AccountService.getAccount(req.params.id)
        .then(function(account) {
            res.send(account);
            //----- then must return a promise here -----
        })
        .catch(function(error) {
            res.status(500).send({'message': error.toString()});
        });
});

      

While this code works great, I'm not comfortable with the function onFulfilled

not returning a promise. This is required by the Promise Specification : then the promise must be returned. Is there a better way to code this?

+3


source to share


1 answer


You misinterpreted the specification.

then

must return the promise

You are confusing the return value then

with the return value of your callback before then

. They are very different.

then

must return the promise and it is. You are calling .catch

on this promise. Nothing you can do can do then

not return a promise, this is part of the implementation of whatever Promise library you use. If the library meets the spec, it then

will return a promise.



The callback then

must not return a promise; no matter what your callback does or does not return, you cannot change the then

return of a promise, it will be regardless. Your callback may return a promise that makes the behavior then

behave differently, but it will return anyway promise

.

Summarizing:

.then( //THIS must return a promise, and it up to the implementation to do so


  function(account) { // THIS (your code) doesn't have to return a promise

      res.send(account);
       //----- then must return a promise here -----
       //       ^ NO, that is wrong
       //
       // We're inside a callback being passed to then, the return value
       // of this function is *not* then return value
  })

      

+2


source







All Articles