0

How do I return an array from a mongojs query. I have the below query executed with nodejs, into a locally running mongodb database. Mongojs is handling the transaction. My question is; how can I return an array from the below function call.

 var databaseUrl = "users";
 var collections = ["users","reports"]; 
 var db = require('mongojs').connect(databaseUrl, collections );
 function usernameFromId(callback){
 db.users.find({}, function(err, result) {
 if(err || !result) console.log("Error");
 else{
 callback(result);
 }
 });
 };
 var x = usernameFromId(function(user){
 return user;
 });
 console.log(x);

Here x is undefined, how can I make a return value such that x will be an array where I can access elements by x.name, x.email etc.

This is what is held in the database.

 { "_id" : ObjectId("4fb934a75e189ff2422855be"), "name" : "john", 
 "password":"abcdefg", "email" : "[email protected]" }
 { "_id" : ObjectId("4fb934bf5e189ff2422855bf"), "name" : "james", 
 "password" :"123456", "email" : "[email protected]" }
asked May 20, 2012 at 18:27

1 Answer 1

2

You can't usefully return with asynchronous functions. You'll have to work with the result within the callback:

usernameFromId(function(user){
 console.log(user);
});

This is due to the nature of asynchronous programming: "exit immediately, setting up a callback function to be called sometime in the future." This means that:

var x = usernameFromId(...);

is evaluated, in its entirety (including setting x to the undefined value returned from usernameFromId), before the callback is actually called:

function (user) {
 return user;
}

And, at least with the current standard of ECMAScript 5, you can't get around this. As JavaScript is single-threaded, any attempt to wait for the callback will only lock up the single thread, keeping the callback and the return user forever pending in the event queue.

answered May 20, 2012 at 18:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.