如何从nodejscallback函数返回值?

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

}

在这里,我试图打印'result1',但总是打印数组与未定义的值。 'result1'是一个被分配在callback函数范围之外的数组。

您不能从asynchronouscallback中返回值。 callback函数通常在声明的函数返回之后的某个时间执行(在调用asynchronous方法后,该函数将继续执行)。 没有callback函数返回。 这是一个简单的例子:

 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 } 

如果您需要依赖asynchronous方法的结果,则需要将需要的代码移到callback中。