48

有人可以给我一个关于如何将 Promise 与猫鼬一起使用的示例。这是我所拥有的,但它没有按预期工作:

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

  });

  return promise;

};

在某些时候,我希望我的数据会出现,但我怎样才能访问它,或者得到它?

4

6 回答 6

48

在当前版本的 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) {  // <- this is the Promise interface.
             console.log(doc);
             next();
         }, function(err) {
             // handle error here.
         });
});

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

于 2014-01-08T03:46:42.990 回答
30

exec()当您调用查询时,Mongoose 已经使用了 Promise。

var promise = Content.find( {route : r }).exec();
于 2014-05-09T08:56:20.577 回答
23

Mongoose 4.0 发行说明

Mongoose 4.0 带来了一些令人兴奋的新功能:浏览器中的模式验证、查询中间件、更新验证以及异步操作的承诺

使用mongoose@4.1,你可以使用任何你想要的 Promise

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');

polyfilling global.Promise 的另一个例子

require('es6-promise').polyfill();
var mongoose = require('mongoose');

所以,你可以稍后再做

Content
  .find({route : r})
  .then(function(docs) {}, function(err) {});

或者

Content
  .find({route : r})
  .then(function(docs) {})
  .catch(function(err) {});

PS猫鼬5.0

如果可用, Mongoose 5.0 将默认使用原生 Promise,否则不使用 Promise。您仍然可以使用 设置自定义承诺库mongoose.Promise = require('bluebird');,但是不支持 mpromise。

于 2015-09-16T07:31:16.700 回答
5

我相信你正在寻找

exports.process = function ( r, callback ) {
  var promise = new mongoose.Promise;
  if(callback) promise.addBack(callback);

  Content.find( {route : r }, function (err, docs) {
     if(err) {
       promise.error(err);
       return;
     }
     promise.complete(docs);

  });

  return promise;

};
于 2012-01-31T14:32:05.507 回答
0

在此页面上:http: //mongoosejs.com/docs/promises.html

标题是Plugging in your own Promises Library

于 2017-01-12T04:14:17.043 回答
-1

像这样使用 bluebird Promise 库:

var Promise = require('bluebird');
var mongoose = require('mongoose');
var mongoose = Promise.promisifyAll(mongoose);

User.findAsync({}).then(function(users){
  console.log(users)
})

这是可以的,例如:

User.findAsync({}).then(function(users){
      console.log(users)
    }).then(function(){
      // more async stuff
    })
于 2015-08-11T18:58:31.150 回答