如何使用猫鼬承诺 - mongo [英] How to use mongoose Promise - mongo

查看:114
本文介绍了如何使用猫鼬承诺 - mongo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给我一个例子,说明如何使用诺基诺的诺言。这是我有的,但它不能按预期工作:

  app.use(function(req,res,next){ 
res.local('myStuff',myLib.process(req.path,something));
console.log(res.local('myStuff'));
next();
});

然后在myLib中,我会有这样的东西:

  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);

});

退货承诺;

};

在某些时候,我期望我的数据存在,但是如何访问它,或者获取在

解决方案

在当前版本的Mongoose中, exec()方法返回一个Promise,所以你可以执行以下操作:

  exports.process = function(r){
return Content.find({route:r})。exec();
}

然后,当您想要获取数据时,应该使其异步:

  app.use(function(req,res,next){
res.local('myStuff' myLib.process(req.path));
res.local('myStuff')
.then(function(doc){//< - 这是Promise界面
控制台.log(doc);
next();
},function(err){
// handle error here。
});
});

有关承诺的更多信息,我最近阅读了一篇精彩的文章:
http://spion.github.io/posts/why-i-am-switching- to-promises.html


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();
});

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?

解决方案

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.
         });
});

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

这篇关于如何使用猫鼬承诺 - mongo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆