How to return value from nodejs callback function?

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 a printable array with an undefined value. 'result1' is an array that is assigned outside the scope of the callback function.

+4
source share
1 answer

You cannot return a value from an asynchronous callback. The callback is usually executed some time after the function in which it was declared returns (this function will continue to execute after the asynchronous method is called). The return function is not returned. Here is 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 to a callback.

+8
source

Source: https://habr.com/ru/post/1446930/


All Articles