1

I'm trying to get a value returned from a function which executes a mongodb query. My problem is that the function returns nothing because the query isn't finished before it returns.

If I try console.log(checkChickenValue(2)); for example I get undefined back. Here is the relevant function:

function checkChickenValue(chickenid) {
    MongoClient.connect(url, function(err, db) {

        var cursor = db.collection('games').find({}, {
            limit : 1,
            fields : {
                _id : 1
            },
            sort : {
                _id : -1
            }
        }).toArray(function(err, docs) {
            var id = docs[0]._id;
            var test = db.collection('games').findOne({
                _id : id
            }, function(err, result) {
                switch(chickenid) {
                case 1:
                    complete(result.chicken1.value);
                    break;
                case 2:
                    complete(result.chicken2.value);
                    break;
                case 3:
                    complete(result.chicken3.value);
                    break;
                case 4:
                    complete(result.chicken4.value);
                    break;
                case 5:
                    complete(result.chicken5.value);
                    break;
                case 6:
                    complete(result.chicken6.value);
                    break;
                case 7:
                    complete(result.chicken7.value);
                    break;
                case 8:
                    complete(result.chicken8.value);
                    break;
                }

            });

        });
    });
    function complete (value)
    {
        return value;
    }
};

How can I let the function wait until complete() is called?

Thanks in advance for your help!

victorkt
  • 13,992
  • 9
  • 52
  • 51
babadaba
  • 814
  • 5
  • 20
  • possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – victorkt Apr 28 '15 at 22:41
  • What is the `complete` function for? – Jason Cust Apr 28 '15 at 22:43
  • Short answer: you can't. See also: http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – JohnnyHK Apr 28 '15 at 22:46

1 Answers1

3

You'll need to return your result via a callback. Add a 'callback' parameter to your function, representing a function that will be called when the result is ready.

function checkChickenValue(chickenid, callback)
{

Then when you have the result, return it via your callback:

switch(chickenid) {
    case 1:
        callback(complete(result.chicken1.value));

Then, to use your function, do something like this:

checkChickenValue(2, function(result){ console.log(result); });
Bazmatiq
  • 614
  • 5
  • 5