如何从nodejs返回值回调函数? [英] How to return value from nodejs callback function?

查看:228
本文介绍了如何从nodejs返回值回调函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


});

}

print'result1'但是它总是打印数组与未定义的值。 '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.

推荐答案

一个异步回调。回调通常在声明返回的函数之后执行一段时间(该函数将在调用异步方法后继续执行)。没有任何回调函数可以返回。这里有一个简单的例子:

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.

这篇关于如何从nodejs返回值回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆