Julio Julio - 3 months ago 36
Node.js Question

Promise and nodejs MongoDB driver

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


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

Answer

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

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