Promise 和 nodejs MongoDB 驱动程序 [英] Promise and nodejs MongoDB driver

查看:25
本文介绍了Promise 和 nodejs MongoDB 驱动程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对 MongoDB 驱动程序做出承诺.我写了以下代码:

I would like to make a promise with the MongoDB driver. I wrote the following code:

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:

Do you have any idea why I don't have the output hello when I call the method connect:

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

推荐答案

手动承诺 API 是危险的,我建议如下:

Manually promisifying an API is dangerous, I suggest something along the lines of:

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

使用 Bluebird 承诺,这看起来像:

With Bluebird promises, that'd look something like:

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

TaskBroker.prototype.connectMongo = function(){
    return MongoClient.connectAsync().then(... 
        // Bluebird will automatically track unhandled errors        
};

这篇关于Promise 和 nodejs MongoDB 驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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