Promise.method() 抛出未处理的拒绝 - 为什么?

Promise.method() throws Unhandled rejection - why?

我不明白为什么我得到一个

Unhandled rejection HttpError
    at null.<anonymous> (/home/makolb/devel/n4v_newsletter/app/controls/publishercontrol.js:31:23)
    at tryCatcher (/home/makolb/devel/n4v_newsletter/node_modules/sequelize/node_modules/bluebird/js/main/util.js:26:23) [...]

which is the line with throw new HttpError(409);在我的代码中:

var PublisherControl = {
    newPublisher: Promise.method(function (email, req) {
        models.Publisher.findOne({where: {email: email}}).then(function (publisher) {
            if (publisher !== undefined) {
                throw new HttpError(409);
            }
        }).then(function () {
            var password = Password.generate(12);
            models.Publisher.create({email: email, password: Password.hashPassword(password)}).then(function (publisher) {
                i_need_this_then_because_i_do_here_something();
                how_do_i_return_a_promise_if_return_publisher_is_not_enough();
                return publisher;
            });
        }).catch(function (err) {
            if (!(err instanceof HttpError)) {
                console.error('catched error: ' + err);
                throw new HttpError(500);
            } else {
                throw err;
            }
        });
    })
};

我的 mocha 测试是这样的:

describe.only('#newPublisher', function () {
    it('should create new publisher', function (done) {
        var Control = require('../../../app/controls/publishercontrol');
        Control.newPublisher('newpublisher@example.com').then(function (publisher) {
            should.exist(publisher);
            should.exist(publisher.email);
            publisher.email.should.eql('newpublisher@example.com');
            publisher.destroy();
            done();
        }).catch(HttpError, function (status) {
            should.not.exist(status);
            done();
        }).catch(done);
    });
});

所以澄清一下,我知道为什么发布者不是未定义的。 我的问题指向蓝鸟部分。我想将该方法用作承诺,并在此承诺上捕获 HttpErrors。 这不应该与 Promise.method(...) 一起使用吗? 你能解释一下吗?

问题是您没有在任何地方返回 Promise,因此没有通过任何 .then/catch 方法过滤决议和拒绝。您也不需要使用 Promise.method,因为您已经在使用 returns 承诺 100% 时间的函数。

var PublisherControl = {
  newPublisher: function (email, req) {
    return models.Publisher.findOne({where: {email: email}})
     .then(function (publisher) {
       if (publisher !== undefined) {
         throw new HttpError(409);
       }
     })
     .then(function () {
       var password = Password.generate(12);
       return models.Publisher.create({
         email: email,
         password: Password.hashPassword(password)
       })
     })
     .catch(function (err) {
       if (!(err instanceof HttpError)) {
         console.error('catched error: ' + err);
         throw new HttpError(500);
       }

       throw err;
     });
   }
};