node.js - Node bluebird 中的 Q.ninvoke 替换

标签 node.js mongoose promise q bluebird

我正在将一个项目从 Q 迁移到 bluebird。 在这个项目中Q.invoke被大量使用。

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

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

重构这段代码并返回相同“种类”的 promise 的最佳 Bluebird 方式是什么? 阅读 bluebird 文档,似乎 promisifyAll 似乎是正确方向的要点。现在我有这个工作,但使调用阻塞:

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

最佳答案

嗯,您可以做几件事。最明显的是令人惊讶的“什么都没有”。

当你不传递 exec 的回调时,Mongoose 已经返回 Promises/A+ promise ,你可以直接同化它们:

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

您可以安全地使用 Bluebird 的 promise , Bluebird 会很乐意吸收它:

Promise.resolve(repo.count(e, q)); // convert to bluebird promise explicitly

someOtherBBPromise.then(function(query){
    return repo.count(entity, query); // `then`able assimilation
});

也就是说, Bluebird 的全面 promise 可能是可取的。因为这个 bluebird 有一个非常强大的 promisifyAll ,可以让你立即 promisify mongoose :

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

关于node.js - Node bluebird 中的 Q.ninvoke 替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28148613/

相关文章:

node.js - 在 Express 中包含 Bootstrap Glyphicons

node.js - Sequelize : Require vs Import

javascript - 程序在 page.evaluate 的嵌套循环中卡住 - Puppeteer - NodeJS

node.js - 如何在 curl 请求中传递 cookie

node.js - 如何在 Mongoose 查询中使用 if 语句?

node.js - 如何获取特定数字字段与所有匹配记录的总和

javascript - 使用 promises 递归检索分页数据

node.js - 使用 req 参数解析对象并保存在 mongoose schema 中

javascript - 如何使用异步 JavaScript getter 和 setter?

JavaScript。等待嵌套的获取 promise