0

だから私は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で作業しているためrent、modules配列から変数を取得する唯一の方法は、と呼ばれるこのコールバック関数を使用することgetRent()です。share問題は、このステップの後、ただし。の外側に値が必要なことですgetRent()。これを行う方法はありますか?

これは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
});

どういうわけか?

4

2 に答える 2

0

ライブラリのwhilstメソッド( )を使用して、これを単純化します。asyncnpm 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関数を使用することもできます。

于 2013-02-14T22:31:15.780 に答える