How to return value from nodejs callback function?

15,192

You can't return a value from an asynchronous callback. The callback is usually executed some time after the function in which it was declared has returned (that function will continue execution after calling an asynchronous method). There is nowhere for a callback function to return to. Here's a simple example:

function doSomething() {
    var x = 10;
    doSomethingAsynchronous(function () {
        // This is a callback function
        return 30; // Where would I return to?
    });
    x += 10; // Execution continues here as soon as previous line has executed
    return x; // doSomething function returns, callback may not have run yet
}

If you need to rely on the result of an asynchronous method, you will need to move the code that requires it into the callback.

Share:
15,192
vcxz
Author by

vcxz

Moovweb, PHP, Node.js, Joomla, Wordpress...

Updated on June 09, 2022

Comments

  • vcxz
    vcxz almost 2 years
    mturk_ops.block = function(callback){
    
    
    mongodb.collection(collectionName, function(err, collection){
    
        collection.distinct('workerId',function(err,result){
            var result1 = [];
            console.log(result.length);
            for(var i=0; i< result.length;i++){
    
                console.log(result[i]);
    
              result1[result[i]] =  collection.count({
                    'workerId':result[i],
                    "judgementStat" : "majority"
                },function(err, count){
                    //  console.log(count);
                  //  globals.push(count);
                    return count ;
                    // console.log( worker + ' majority : ' + count);
    
                });
    
            }
    
        console.log(result1);
        });
    
    
    });
    

    }

    Here I am trying to print 'result1' but its always printing array with undefined value. 'result1' is an array which is assigned out of the scope of callback function.

  • vcxz
    vcxz over 11 years
    Can I assign value(here 30) to variable x inside callback function?
  • rdrey
    rdrey over 11 years
    @venuwale yes, you can, but the outer function (doSomething) will be done (return 20) before your inner asynchronous function has taken effect (setting x to 30).
  • jagc
    jagc over 8 years
    @james-allardice so how do you use anything computed within the inner function ( doSomethingAsynchronous ) outside of it?