Return value from a mongodb call from nodejs

2020-08-06 15:07发布

问题:

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" : "john@example.com" }
 { "_id" : ObjectId("4fb934bf5e189ff2422855bf"), "name" : "james", 
 "password" :"123456", "email" : "james@example.com" }

回答1:

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.