繁体   English   中英

Node.js中的功能范围和回调

[英]Functionscope and Callbacks in Node.js

所以我必须循环计算一些share 在该循环的每次迭代中,我都必须从数组中获取一个名为rent的变量。 因此,我从数据库中划分了calculate函数。

var calculate = function() {
    while(count < 100) {
        var share = 50;
        var shareArray = [];

        for(var i = 0; i < 100; i++) {

            var pension = share*2; // mathematical stuff
            // Gets a rent from a database and returns it in a callback
            getRent(modules, share, function(rent) {
                share = rent*foo; // some fancy mathematical stuff going on here
                // I need to get the share variable above out of its function scope
            });
                    // I need the share variable right here
            shareArray.push(share);     // the value of share will be for i = 0: 50, i= 1: 50 ...
                                        // This is not what i want, i need the share value from getRent()
        }
        count++;
    }
}

现在,您可能会看到以下问题。 因为我正在使用node.js,所以从modules数组获取rent变量的唯一方法是通过名为getRent()回调函数。 问题是,我需要在此步骤之后但在getRent()之外的share值。 有什么办法可以做到吗?

这是getRent() -函数:

var getRent = function(modules, share, callback) {
        // Searching for a fitting rent in the modules array
        // Just assume this is happening here
        callback(rent);
};

所以问题是:我如何“返回” share

getRent(modules, share, function(rent) {
                    share = rent*foo; // some fancy mathematical stuff going on here
                    // I need to get the share variable above out of its function scope
});

以任何方式?

如果getRent是异步的,则无法同步获取结果。 根本上,您不知道getRent最终将提供给它的回调值,直到它最终返回它为止。 因此,这不是功能范围的问题,而是时间的问题。 您只需要等待getRent做它的事情,然后才能获得rent的价值。 您需要重构代码,以使calculate也保持异步。

就像是:

// Refactor calculate to be async:
function calculate(cb) {
    var data = [];
    for ( var i=0; i<100; i++ ) {
        getRent(function (rent) {
            data.push(rent);
            if ( data.length === 100 ) cb(data);
        });
    }
}

// And then use it async:
calculate(function (data) {
    // data array arrives here with 100 elements
});

上面的答案可能与您使用香草JS实现它的方式相似。 从长远来看,使用像miggs这样的async库可能是一个好主意。 但是就像我说的那样,如果您使用普通JS或async库,那么您必须在该代码和调用它的代码中都必须重构为异步,这一事实无处可逃。

你想使用whilst该方法async库( npm install async ),以简化这个:

var count = 0;
var shareArray = [];

async.whilst(
    function () { 
        return count < 100; 
    },
    function (next) {
        count++;
        getRent(function(rent) {
            // What does modules do anyway??
            // Dont know where foo comes from...
            shareArray.push(rent*foo); // some fancy mathematical stuff going on here
            next();
        });
    },
    function (err) {
        console.log(shareArray);
        // Do sth. with shareArray
    }
);

如果可以并行请求所有100个调用,则还可以使用parallel函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM