How to return the value from an asynchronous function in node.js

advertisements

I have recently started learning MEAN. I have the following code to return collection of document of MongoDb.

var giveData = function()
{
var mongodb = require('mongodb');
var mongoClient = mongodb.MongoClient;

var url = 'mongodb://127.0.0.1:27017/ngs'  

var retVal;  // this is a return value which will contain documents

mongoClient.connect(url, function(err, db)
                        {
                            if (err)
                            {
                                console.log(err)
                            }else
                            {
                                 db.collection('employees').find().toArray(
                                    function(err, doc)
                                    {
                                        if(err)
                                        {
                                            throw err;
                                        }else{
                                            console.log(doc); // this works fine
                                            retVal = doc;     // this does not assign the value ????  why so ??

                                        }

                                    }

                                );

                            }
                        }
                    )

console.log("Message from lib");
console.log(retVal);  // this returns undefined
console.log("-----------------");

return retVal;  // this may return data from the server but is returning undefined 

}

 module.exports ={  showMessage: showMessage,
                        giveData: giveData
                    }

From the remarks it is clear that I want collection of documents from MongoDb database into a variable called retVal, which I have assigned value of doc on correct process.

Although the document is displayed successfully but somehow it does not get assigned to variable called retVal.

Please throw some light on the subject so that collection of document is returned from the function called giveData()

Thanks and regards.


In this section

var retVal;  // this is a return value which will contain documents

retVal is undefined

And at the bottom

return retVal;  // this may return data from the server but is returning undefined

retVal is still undefined because the call to mongoClient.connect is asynchronous

You're returning the value of retVal at a specific moment. This value will not change.

You should pass a callback function to giveData so you can access the returned data once it is received.

var giveData = function(callback) {
  var mongodb = require('mongodb');
  var mongoClient = mongodb.MongoClient;

  var url = 'mongodb://127.0.0.1:27017/ngs' 

  mongoClient.connect(url, function(err, db) {
    if (err) {
      callback(err)
    } else {
      db.collection('employees').find().toArray(function(err, doc) {
        if(err) {
          callback(err)
        } else {
          callback(null, doc)
        }
      })
    }
  }

}

module.exports = {
  showMessage: showMessage,
  giveData: giveData
}

And than use it like so

giveData(function(err, doc) {
  if(err) {
    // handle error
  } else {
    // you can now use doc!
  }
})