node.js - Express 框架和 Promises - 从路由处理程序返回什么?

标签 node.js express promise

我一直在为我的 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/

相关文章:

ios - node ios socket.io SSL 适用于 xcode 调试但不适用于 ipa 安装

javascript - 带有路由器的 Node.js (Express) 错误处理中间件

javascript - javascript对象没有内置函数hasOwnProperty

javascript - 使用自定义字符串更新 Firebase

node.js - 无法启动 nodejs 应用程序 - 需要错误 : npm. load()

Javascript -Uncaught promise 被拒绝,即使它已经被拒绝

javascript - js promise 问题 (bluebird)

javascript - Javascript中promise和@@iterator的问题

node.js - Google Cloud -> Node 服务器 -> React 客户端之间的文件下载,无需保存在服务器本地

node.js - 如何判断使用 Node.js 选择了哪个单选按钮