Mohammad Abdullah
Mohammad Abdullah

Reputation: 31

the complications in javascript node.js?

I've learned node.js and javascript lately. I loved node.js a lot, but I am working on a project coded in node.js, mongodb, cordova etc. I notice that I needed to use Promise Object in the code a lot.

I create a module in the project to query the db and bring results. In every exported function I need to declare a local function, then use promise, for example:

I have the following local functions in the Module:

var Initialize = function() {
  return new Promise(function(resolve, reject) {
    try {
      MongoClient.connect("db_url_conn", function(err, database) {
        if (err) return console.log(err)
        db = database;
        return resolve(db);
      })
    } catch (e) {
      console.error(e);
    }
  });
};

then in every exported function in the module I needed to use:

mongoOperation.prototype.getLength = function() {
  Initialize(function(db) {
    return db;
  }).then(function(db) {
    getSize(db).then(function(length) {
      console.log(length);
    });
  });
}

The Question is:

  1. Is that normal according to the nature of node.js and JavaScript nature to use promise a lot?
  2. Do I have any other choices to fulfill that?

Upvotes: 0

Views: 102

Answers (1)

robertklep
robertklep

Reputation: 203519

Since MongoClient.connect() already returns a promise, you can simplify your code:

var Initialize = function() {
  return MongoClient.connect("db_url_conn");
};
...
Initialize().then(function(db) { ... });

However, this will create a new client each time you call Initialize, where you should be reusing the client for better performance and to leverage the built-in connection pool:

var client = MongoClient.connect("db_url_conn");
var Initialize = function() { return client };

Upvotes: 2

Related Questions