Node.js Promise和nodejs MongoDB驱动程序

Node.js Promise和nodejs MongoDB驱动程序,node.js,mongodb,promise,Node.js,Mongodb,Promise,我想和MongoDB司机做个承诺。我编写了以下代码: var TaskBroker = function () { this.queueName = 'task_queue'; this.rabbit = {}; this.mongo = {}; }; TaskBroker.prototype.connectRabbit = function() { var self = this; return amqp.connect('amqp://localhost')

我想和MongoDB司机做个承诺。我编写了以下代码:

var TaskBroker = function () {
  this.queueName = 'task_queue';
  this.rabbit = {};
  this.mongo = {};
};

TaskBroker.prototype.connectRabbit = function() {
  var self = this;

  return amqp.connect('amqp://localhost')
    .then(function(connection) {
      self.rabbit.connection = connection;
      return connection.createChannel()
    })
    .then(function(channel) {
      self.rabbit.channel = channel;
      return channel.assertQueue(self.queueName, {durable: true});
    })
};

TaskBroker.prototype.connectMongo = function() {
  console.log('Connect Mongo');
  var self = this;
  var defer = q.defer();
  MongoClient.connect('mongodb://127.0.0.1:27017/test', {}, defer.makeNodeResolver());
  return  defer.promise.then(function(db) {
    self.mongo.db = db;
    console.log('hello');
    return 42;
  });
};

TaskBroker.prototype.connect = function () {
  var self = this;
  return this.connectRabbit()
    .then(self.connectMongo);
};
当我调用方法
connect
时,你知道为什么我没有输出吗
hello

taskBroker.connect()
  .then(function(result) {
    console.log('Disconnected');
    taskBroker.disconnect();
});

手动提示API是危险的,我建议如下:

TaskBroker.prototype._connectMongo = Q.nfcall(MongoClient.connect,
                                             'mongodb://127.0.0.1:27017/test',
                                            {});
TaskBroker.prototype.connectMongo = function(){
   return this._connectMongo().then(function(db){
       console.log("Hello");
       // self.stuff...
       return 42;
   }).catch(function(e){
       console.err("connection error",e); // log the connection error, or handler err
       throw e; // don't mark as handled, propagate the error.
   });
};
有了蓝鸟的承诺,这看起来像:

var MongoClient = Promise.promisifyAll(require("mongodb").MongoClient);

TaskBroker.prototype.connectMongo = function(){
    return MongoClient.connectAsync().then(... 
        // Bluebird will automatically track unhandled errors        
};
蒙哥达 对于处理mongodb驱动程序,我建议使用(免责声明:是我写的)。这相当于承诺而不是回调。它还允许您将“连接”操作视为同步操作,方法是立即返回可与之交互的对象,并在内部等待连接。真正好的一点是,它与官方mongodb文档相匹配,因此您可以使用该文档了解如何使用它

一般情况 通常,获取一个不返回承诺的API并获取一个返回承诺的API应该使用承诺构造函数来完成。e、 g

function readFile(filename, enc){
  return new Promise(function (fulfill, reject){
    fs.readFile(filename, enc, function (err, res){
      if (err) reject(err);
      else fulfill(res);
    });
  });
}
如果您使用Q,您应该执行以下操作:

function readFile(filename, enc){
  return q.promise(function (fulfill, reject){
    fs.readFile(filename, enc, function (err, res){
      if (err) reject(err);
      else fulfill(res);
    });
  });
}
帮助方法 包括Q在内的许多库都提供了特殊的助手方法,用于调整node.js样式的回调方法以返回承诺。e、 g

var readFile = q.denodeify(fs.readFile);
或与:

如果你想了解更多关于如何创建和使用Promise对象的信息(而不是特定于Q),我建议你去看看(diclaimer:我写的)。

node mongodb驱动程序引入了对Promise的一流支持

以下是官方文件中的一个示例:

// A simple query showing skip and limit using a Promise.

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

  // Create a collection we want to drop later
  var collection = db.collection('simple_limit_skip_query_with_promise');
  // Insert a bunch of documents for the testing
  collection.insertMany([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {w:1}).then(function(result) {

    // Peform a simple find and return all the documents
    collection.find({})
      .skip(1).limit(1).project({b:1}).toArray().then(function(docs) {
        test.equal(1, docs.length);
        test.equal(null, docs[0].a);
        test.equal(2, docs[0].b);

        db.close();
    });
  });
});
默认情况下,将使用该库,但您可以在创建DB连接时覆盖该库:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/test', {
  promiseLibrary: require('bluebird')
}, function(err, db) {
  // ...

您使用的promise库是哪一个?@FlorianMargaine它是基于makeNoreResolver和旧的延迟模式的Q。我使用的是
Q
库。@Julio如果您执行一个正常的DB调用,但没有对数据库的承诺,它能工作吗?谢谢。我用
this替换了
this.\u connectMongo()
。\u connectMongo
返回这个.connectRabbit()。然后(self.connectMongo)
by
返回这个.connectRabbit().then(self.connectMongo())而且它现在很有魅力。谢谢你这个非常有建设性的回答。
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/test', {
  promiseLibrary: require('bluebird')
}, function(err, db) {
  // ...