0

I want to return some data from mongodb in a function. The body of the functions looks like this:

var name = '';
var ret = this.collection.findOne({"socket_id" : socket_id}).on('success', function(doc) {
    name = doc.name;
    console.log("name inside mongo callback is not empty" + name);
});
console.log("name here is empty" + name);

If I log the data in the console, the callback displays the data properly, but if I return form callback, I cannot seem to catch it from where I call the function. I suspect it has something to do with node.js being asynchronous and stuff, but how can I tackle this? Any help would be appreciated

allisius
  • 395
  • 3
  • 18

1 Answers1

1

So it turns out it was exactly because I was trying to get a synchronous response to an otherwise asynchronous functions. If you stumble upon this problem, I would refer you to the answer to this question:

How to return value from an asynchronous callback function?

It has all the answers you need on how to perform such an operation

Community
  • 1
  • 1
allisius
  • 395
  • 3
  • 18