babadaba
babadaba

Reputation: 814

node.js function should only return after mongodb query finished

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!

Upvotes: 1

Views: 1685

Answers (1)

Bazmatiq
Bazmatiq

Reputation: 634

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); });

Upvotes: 3

Related Questions