如何使用猫鼬 Promise - mongo [英] How to use mongoose Promise - mongo
问题描述
谁能给我举个例子,说明如何在猫鼬中使用 Promise.这是我所拥有的,但它没有按预期工作:
Can someone give me an example on how to use a Promise with mongoose. Here is what I have, but its not working as expected:
app.use(function (req, res, next) {
res.local('myStuff', myLib.process(req.path, something));
console.log(res.local('myStuff'));
next();
});
然后在 myLib 中,我会有这样的东西:
and then in myLib, I would have something like this:
exports.process = function ( r, callback ) {
var promise = new mongoose.Promise;
if(callback) promise.addBack(callback);
Content.find( {route : r }, function (err, docs) {
promise.resolve.bind(promise)(err, docs);
});
return promise;
};
在某些时候,我希望我的数据会出现,但我该如何访问或获取它?
At some point I am expecting my data to be present, but how can I access it, or get at it?
推荐答案
在当前版本的 Mongoose 中,exec()
方法返回一个 Promise,因此您可以执行以下操作:
In the current version of Mongoose, the exec()
method returns a Promise, so you can do the following:
exports.process = function(r) {
return Content.find({route: r}).exec();
}
然后,当你想要获取数据时,你应该让它异步:
Then, when you would like to get the data, you should make it async:
app.use(function(req, res, next) {
res.local('myStuff', myLib.process(req.path));
res.local('myStuff')
.then(function(doc) { // <- this is the Promise interface.
console.log(doc);
next();
}, function(err) {
// handle error here.
});
});
关于 Promise 的更多信息,我最近阅读了一篇精彩的文章:http://spion.github.io/posts/why-i-am-切换到promises.html
For more information about promises, there's a wonderful article that I recently read: http://spion.github.io/posts/why-i-am-switching-to-promises.html
这篇关于如何使用猫鼬 Promise - mongo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!