5

我开始将我的回调代码转换为 Sails.js 中的承诺,但我不明白如何引发自定义错误并在承诺链中处理它们。Sails.js 使用 Q 作为其承诺库。

User.findOne({email: req.param('professorEmail'), role: 'professor'})
    .then(function (user) {
      if (user) {
        return Course.create({
          user_id: user.id,
          section: req.param('section'),
          session: req.param('session'),
          course_code: req.param('course_code')
        });
      } else {
        // At this point `user` is undefined which means that no professor was found so I want to throw an error.
        // Right now the following statement does throw the error, but it crashes the server.
        throw new Error('That professor does not exist.');
        // I want to be able to handle the error in the .fail() or something similar in the promise chain.
      }
    }).then(function (createSuccess) {
      console.log(createSuccess);
    }).fail(function (err) {
      console.log(err);
    });

现在.fail()永远不会调用,因为抛出的错误会使服务器崩溃。

4

2 回答 2

9

使用.catch()而不是.fail().

于 2014-09-30T12:51:39.013 回答
6

根据您的测试, Waterline complete Q promise object在第一次之后的说法then似乎是不真实的。我自己也验证了它并找到了解决方法。

你可以这样做 :

var Q = require('q');
[...]
Q(User.findOne({email: req.param('professorEmail'), role: 'professor'}))
.then(function (user) {
  if (user) {
    return Course.create({
      user_id: user.id,
      section: req.param('section'),
      session: req.param('session'),
      course_code: req.param('course_code')
    });
  } else {
    // At this point `user` is undefined which means that no professor was found so I want to throw an error.
    // Right now the following statement does throw the error, but it crashes the server.
    throw new Error('That professor does not exist.');
    // I want to be able to handle the error in the .fail() or something similar in the promise chain.
  }
}).then(function (createSuccess) {
  console.log(createSuccess);
}).fail(function (err) {
  console.log(err);
});

这将返回一个真正的 Q 承诺。

于 2013-11-13T17:22:33.610 回答