Node.js承诺与mongoskin [英] Node.js promises with mongoskin
问题描述
我正在尝试避免在制作mongodb查询时使用回调。我正在使用mongoskin来打电话,如下所示:
I'm trying to avoid using callbacks when making mongodb queries. I'm using mongoskin to make calls like so:
req.db.collection('users').find().toArray(function (err, doc) {
res.json(doc);
});
在许多情况下,我需要进行多个查询,所以我想使用Node.js promise库,但是不知道如何把这些功能作为承诺。我看到的大多数例子对于 readFile
这样的事情来说是微不足道的,我猜这个例子我需要以某种方式包装到Array?这可以完成还是必须由mongoskin实现?
In many cases I need to make multiple queries so I want to use Node.js promise library but I'm not sure how to wrap these functions as promises. Most of the examples I see are trivial for things like readFile
, I'm guessing in this case I would need to wrap toArray somehow? Can this be done or would have to be something implemented by mongoskin?
一个例子可以是任何一组回调,find / insert,find / find / insert,find /更新:
An example could be any set of callbacks, find/insert, find/find/insert, find/update:
req.db.collection('users').find().toArray(function (err, doc) {
if (doc) {
req.db.collection('users').find().toArray(function (err, doc) {
// etc...
});
}
else {
// err
}
});
推荐答案
您可以用蓝鸟来表达整个模块:
You can promisify the entire module like so with bluebird:
var Promise = require("bluebird");
var mongoskin = require("mongoskin");
Object.keys(mongoskin).forEach(function(key) {
var value = mongoskin[key];
if (typeof value === "function") {
Promise.promisifyAll(value);
Promise.promisifyAll(value.prototype);
}
});
Promise.promisifyAll(mongoskin);
这只需要在您的应用程序中一次完成,而不需要在应用程序中的任何位置
This only needs to be done in one place for one time in your application, not anywhere in your application code.
之后,您只需使用正常方式,除了Async后缀,并且不传递回调:
After that you just use methods normally except with the Async suffix and don't pass callbacks:
req.db.collection('users').find().toArrayAsync()
.then(function(doc) {
if (doc) {
return req.db.collection('users').find().toArrayAsync();
}
})
.then(function(doc) {
if (doc) {
return req.db.collection('users').find().toArrayAsync();
}
})
.then(function(doc) {
if (doc) {
return req.db.collection('users').find().toArrayAsync();
}
});
所以再次,如果你调用一个函数, / p>
So again, if you call a function like
foo(a, b, c, function(err, result) {
if (err) return console.log(err);
//Code
});
承诺返回版本称为:
fooAsync(a, b, c).then(...)
(未收到的错误会自动记录,所以如果您只需要登录,则不需要检查它们)
(Uncaught errors are automatically logged so you don't need to check for them if you are only going to log it)
这篇关于Node.js承诺与mongoskin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!