向Bluebird promise添加方法



我已经承诺了Mongoose。我有一些扩展Mongoose Query的方法,现在需要将其添加到Bluebird中。我不介意扩展Mongoose,但不想对这个更gobal的库采取同样的方法。通过查阅这些文件,我看到了一些潜力,但我不确定。

我想尽量做到以下几点:

Model.findAsync().toCustom();

toCustom基本上是toJSON的一种形式,它1)执行查询,2)自定义输出结果/创建自定义错误等。

实现上述目标最干净的方法是什么?我想避免每次都这样做:

Model.findAsync().then(function(docs) {
  return toCustom(docs);
}, function(err) {
  return toCustom(err);
});

你明白了。。。

Bluebird实际上直接支持您的用例。如果你需要发布一个以你自己的自定义方式扩展bluebird的库,你可以通过以下操作获得一份新的bluebird副本:

var Promise = require("bluebird/js/main/promise")();
Promise.promisifyAll(require("mongoose")); // promisify with a local copy
Promise.prototype.toCustom = function(){
   return this.then(toCustom, toCustom); // assuming this isn't just `.finally`
};

您可能还想以某种方式导出它。这个功能是为图书馆作者和获得蓝鸟的孤立副本而设计的。请参阅wiki中的库作者部分。

最新更新