I have been using the following promise-based template 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 perfectly fine, I am uncomfortable that the onFulfilled function is not returning a promise. This is required by the Promise Specification: then must return a promise. Is there a better way to code this?
You've misinterpreted the spec.
thenmust return a promise
You are confusing the return value of then with the return value of your callback to then. They are very different.
then must return a promise, and it is. You're invoking .catch on that promise. Nothing you can do can make then not return a promise, it's part of the implementation of whatever Promise library you're using. If the library conforms to the spec, then will return a promise.
Your callback to then does not have to return a promise; whatever your callback does or does not return cannot change then's returning of a promise, it will regardless. Your callback may return a promise which causes then to behave differently, but it will still return a promise.
To summarize:
.then( //THIS must return a promise, and it's 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's return value
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With