我一直在为我的 Express 路由处理程序使用以下基于 promise 的模板:
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()});
});
});
虽然这段代码工作得很好,但令我感到不安的是 onFulfilled
函数没有返回 promise 。这是 Promise Specification 所要求的: 然后必须返回一个 promise。有没有更好的编码方式?
最佳答案
您误解了规范。
then
must return a promise
您混淆了 then
的返回值与您的 回调 到 then
的返回值。它们非常不同。
then
必须返回一个 promise ,确实如此。您正在根据该 promise 调用 .catch
。您所做的任何事情都不能使 then
不 返回一个 promise,它是您正在使用的任何 Promise 库的实现的一部分。如果库符合规范,then
将返回一个 promise 。
您对 then
的回调不必必须返回 promise ;无论你的回调返回或不返回什么都不能改变 then
的 promise 返回,它会无论如何。您的回调可能返回一个导致then
行为不同的 promise ,但它仍然会返回一个 promise
。
总结:
.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
})
关于node.js - Express 框架和 Promises - 从路由处理程序返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31272671/