Bluebird 承诺不包装节点样式函数

Bluebird promisify not wrapping node style function

我很困惑为什么 Bluebird 的 Promise.promisify 没有承诺我的查询函数,因为它像大多数节点样式函数一样接受回调。难道是 Mongoose 的 aggregation() 方法破坏了代码?

function query(callback) {
  model.aggregate([{$sort:{a: -1}}], function(err, items) {
    if (err) {
      console.log(err);
    }
    let mostA = items[0].a;
    Caller.aggregate([{$sort:{b: -1}}], function(err, items) {
      if (err) {
        console.log(err);
      }
      let mostB = items[0].b;
      callback({mostA: mostA, mostB: mostB});
    });
  });
};

let most = Promise.promisify(query);

most()
.then((data) => {
  // do something
})
.catch((err) => {
  console.log('err:', err); // I always get an error.
});

这不是节点样式的回调。节点样式回调必须执行以下操作:

  1. 回调必须是方法的最后一个参数(你在这方面做得很好)。
  2. 回调必须有两个参数(你不擅长这个)
  3. 回调的第一个参数必须是一个错误值,只要有错误(你不擅长这个)就为真。
  4. 回调的第二个参数必须是返回的任何数据(如果有的话)。

此外,您的 query() 函数没有进行正确的错误处理。它需要以错误值作为第一个参数调用回调,然后停止进一步处理。

所以,当您这样做时:

callback({mostA: mostA, mostB: mostB});

您告诉回调有一个错误,因为您将第一个参数作为真值传递。

如果你想让它成为正确的形式,你会这样做:

 callback(null, {mostA: mostA, mostB: mostB});