【问题标题】:How to return value from nodejs callback function?如何从nodejs回调函数返回值?
【发布时间】:2012-11-19 11:17:09
【问题描述】:
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' 是一个数组,它被分配到回调函数的范围之外。

【问题讨论】:

  • 不能退货。它必须通过新的回调传递。

标签: javascript node.js callback


【解决方案1】:

您不能从异步回调中返回值。回调通常在声明它的函数返回后的某个时间执行(该函数将在调用异步方法后继续执行)。回调函数无处返回。这是一个简单的例子:

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
}

如果您需要依赖异步方法的结果,则需要将需要它的代码移动到回调中。

【讨论】:

  • 我可以在回调函数中为变量 x 赋值(这里是 30)吗?
  • @venuwale 是的,你可以,但是外部函数 (doSomething) 将在你的内部异步函数生效之前完成 (return 20)(将 x 设置为 30)。
  • @james-allardice 那么你如何使用在内部函数( doSomethingAsynchronous )之外计算的任何东西?
猜你喜欢
  • 2021-06-01
  • 2011-11-13
  • 2019-07-25
  • 2012-03-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2020-12-03
  • 1970-01-01
相关资源
最近更新 更多