Q.ninvoke节点蓝鸟的replace

我从Q迁移到蓝鸟项目。 在这个项目中,Q.invoke被使用了很多。

例如在这样的中心方法中:

repo.count = function(entity,query) { // entity is a mongoose model var command = query = entity.find(query).count(); return Q.ninvoke(command, 'exec'); }; 

什么是最好的蓝鸟重构这个代码的方式,并返回相同的“种”承诺? 阅读蓝鸟文件,似乎promisifyAll似乎是在正确的方向点。 现在,我有这个工程,但阻止呼叫:

 repo.count = function*(entity,query) { entity = bluebird.promisifyAll(entity); // this needs to be moved somewhere central return yield entity.find(query).count(); }; 

那么,你可以做几件事情。 最明显的是令人惊讶的“没有”。

当你不传递execcallback时,Mongoose已经返回Promises / A + promise,你可以把它们同化:

 repo.count = function(entity,query) { // entity is a mongoose model return entity.find(query).count().exec(); // return promise }; 

你可以放心的使用蓝鸟这个承诺,

 Promise.resolve(repo.count(e, q)); // convert to bluebird promise explicitly someOtherBBPromise.then(function(query){ return repo.count(entity, query); // `then`able assimilation }); 

也就是说,可以期望有全面的蓝鸟承诺。 对于这个蓝鸟有一个非常强大的promisifyAll ,让你立即promisifymongoose:

 var Promise = require("bluebird"); var mongoose = Promise.promisifyAll(require("mongoose")); // everything on mongoose promisified someEntity.saveAsync(); // exists and returns bluebird promise