2012-11-19 58 views
4
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); 
    }); 


}); 

}如何從nodejs回調函數中返回值?

在這裏,我試圖打印「RESULT1」,但它與不確定的價值始終打印陣列。 'result1'是一個分配在回調函數範圍外的數組。

+1

你不能返回。它必須以新的回調傳遞。 – Max

回答

8

不能從異步回調返回值。該回調通常在聲明返回的函數執行一段時間後執行(該函數將在調用異步方法後繼續執行)。有無處回調函數返回。這裏有一個簡單的例子:

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 
} 

如果您需要依靠異步方法的結果,你將需要移動需要它步入回調的代碼。

+0

我能否確定值(這裏是30),回調函數內變量x? – vcxz

+1

@venuwale是的,你可以,但外部函數('doSomething')會做你內心的異步函數之前('回報20')已生效(x設置爲30)。 – rdrey

+0

@詹姆斯 - 阿勒代斯那麼你如何使用任何在它之外的內部函數(doSomethingAsynchronous)中計算? – jagc