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

时间:2015-07-07 15:15:58

标签: 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 Specification所必需的:然后必须返回一个承诺。有没有更好的方法来编码呢?

1 个答案:

答案 0 :(得分:2)

您误解了规范。

  

then必须返回承诺

您将then的返回值与回调的返回值混淆为then。他们是非常不同的。

then必须返回一个承诺,它就是。您在该承诺上调用.catch。您无法做任何事情可以使then 而不是返回承诺,它是您正在使用的任何Promise库的实现的一部分。如果库符合规范,then将返回一个承诺。

您对then的回复必须返回承诺;无论你的回调做什么或不回来都不能改变then回复承诺,它将无论如何。您的回调可能会返回一个承诺,导致then行为不同,但仍会返回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
  })