Bluebird 和 Mongoose:警告:在处理程序中创建了承诺,但未从中返回

Bluebird and Mongoose: Warning: a promise was created in a handler but was not returned from it

我在我的项目中使用猫鼬和蓝鸟。即使我更正了所有代码,这个警告也无处不在。它仍然发生。

exports.middleware = function (req, res, next, id) {
  Account.findById(id).exec().then(function(account) {
    if (!account) {
      return res.status(404).send({
        message: 'No account with that identifier has been found'
      });
    }
    req.account = account;
    next();
  }).catch(function(err) {
    return next(err);
  });
};

在检查 lib/query.js 的 mongoose 源代码后,我注意到 exec() 回调函数中存在一些问题

https://github.com/Automattic/mongoose/blob/master/lib/query.js#L2243

query.prototype.exec = function exec(op, callback) {
  ...
  if (callback) {
    promise.then(
      function() {
        callback.apply(null, _results);
      },
      function(error) {
        callback(error);
      });
  }
  ...
}

promise.then()中没有return。所以在猫鼬解决这个问题之前。我只是避免在我的代码中使用 exec(callback) 。那么大家都会很开心。