javascript 如何从nodejs回调函数返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13452660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:49:52  来源:igfitidea点击:

How to return value from nodejs callback function?

javascriptnode.jscallback

提问by vcxz

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.

在这里,我试图打印“result1”,但它总是打印具有未定义值的数组。'result1' 是一个数组,它被分配到回调函数的范围之外。

回答by James Allardice

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.

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