0

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?
3
  • 1
    1. Yes, it's async by nature. 2. Observables? Commented Aug 28, 2016 at 7:31
  • 3
    Your second code block isn't using Initialize correctly. The function you're passing into Initialize is never called, as Initialize does nothing with any arguments. The then part is also non-optimal. Instead: jsfiddle.net/mp29Lvze (pastie.org is down). Commented Aug 28, 2016 at 7:34
  • yes , thanks , it was working any way , but that wasn't the the discussion , we are discussing here about the complications to get a value !! Commented Aug 28, 2016 at 7:40

1 Answer 1

2

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 };
Sign up to request clarification or add additional context in comments.

3 Comments

Oh, sure. I'm sorry.
@robertklep actually I did that , but when I execute other function depending on the MongoClient.connection , it threw an error , undefined , so I am obligated to use this first to be sure that MongoClient did the connection !!
@MohammadAbdullah I don't see how this code can return an undefined value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.