簡體   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