为什么我可以在链的中间捕获一个 Bluebird 来停止其余的链执行

Why can I get a Bluebird catch in the middle of chain stop the rest of the chain execution

我正在构建这个承诺链。目标是让第一个操作检查数据库中某个字段的唯一性,然后如果唯一,则保存该对象。但是如果对象不是唯一的,它不应该保存,并且应该return一个错误响应。

function(request, reply) {
  var payload = request.payload;

  checkThatEmailDoesNotExist().then(saveUser)

  function checkThatEmailDoesNotExist() {
    return User.where({email: payload.email}).countAsync()
      .then(function(count) {
        if (count > 0) {
          throw Boom.badRequest('The email provided for this user already exists')
        }

        return null;
      })
      .catch(function(err) { // ~This catch should stop the promise chain~
        reply(err);
      })
  }

  function saveUser() {
    // ~But instead it is continuing on to this step~
    return User.massAssign(request.payload).saveAsync()
      .spread(function(user, numAffected) {
        return reply(user);
      })
      .catch(function(err) {
        server.log(['error', 'api', 'auth'], err);
        throw Boom.badRequest('Object could not be saved to database');
      });
  }
}

如果在 checkThatEmailDoesNotExist() 中抛出错误,则 catch() 应该 return 错误,并停止处理原始承诺链的其余部分。

catch() 没有那样做,而是触发,然后继续移动到 saveUser() 函数。

你混合了承诺和回调,这是一个可怕的反模式。调用者将简单地使用 返回的承诺,无需手动将事情连接回回调。

function save(request) {
  var payload = request.payload;

    return User.where({email: payload.email}).countAsync()
      .then(function(count) {
        if (count > 0) {
          throw Boom.badRequest('The email provided for this user already exists')
        }

        return User.massAssign(request.payload).saveAsync()
      })
      .get(0)
      /* equivalent to 
      .spread(function(user, numAffected) {
        return user;
      }) */
      .catch(Promise.OperationalError, function(err) {
        server.log(['error', 'api', 'auth'], err);
        throw Boom.badRequest('Object could not be saved to database');
      });
}

用法:

save(request).then(function(user) {
    response.render(...)
}).catch(function(e) {
    response.error(...)
})

如果您想公开一个回调 api,明智的做法是在现有承诺 api 的末尾加入节点化,然后收工:

function save(request, callback) {
  var payload = request.payload;

    return User.where({email: payload.email}).countAsync()
      .then(function(count) {
        if (count > 0) {
          throw Boom.badRequest('The email provided for this user already exists')
        }

        return User.massAssign(request.payload).saveAsync()
      })
      .get(0)
      /* equivalent to 
      .spread(function(user, numAffected) {
        return user;
      }) */
      .catch(Promise.OperationalError, function(err) {
        server.log(['error', 'api', 'auth'], err);
        throw Boom.badRequest('Object could not be saved to database');
      })
      .nodeify(callback);
}

save(request, function(err, user) {
    if (err) return response.error(...);
    response.render(...);
});