如何设置变量异步瀑布?

How to set a variable async waterfall?

我在设置变量或至少 return 在异步瀑布中设置变量时遇到问题。我知道你不能在异步中 return 但我对我的变量 jsonFinal 做了一个回调,它进入了下面数据下的函数。

function getIndividualMatchJSONObjHelper(matchData, matchParticipantData, indexIter) {
var individualMatchURL = 'https://na1.api.riotgames.com/lol/match/v3/matches/' + matchData.matchID[indexIter] + '?api_key=' + API_KEY;
var jsonFinal;
async.waterfall([
    function(callback) {
          request(individualMatchURL, function(err, response, body) {
            if(!err && response.statusCode == 200) {
                var json = JSON.parse(body);
                for (var j = 0; j < 10; j++) {
                    if (matchData.championID[indexIter] == json['participants'][j].championId) {
                        jsonFinal = json['participants'][j];
                        callback(null, jsonFinal);
                    }
                }
            } 
            else {
                console.log(err);
                }
        });
    }
],
function(err, data) {
    if(err) {
        console.log(err);
    }
    else {
        jsonFinal = data;
    }
});
console.log(jsonFinal);
return jsonFinal; 
}

我怎样才能正确获取 return jsonFinal 的函数?

与任何异步操作一样,您只能在回调中获取变量。因此,修改您的函数以也接受回调。

function getIndividualMatchJSONObjHelper(matchData, matchParticipantData, indexIter, callback) {
    var individualMatchURL = 'https://na1.api.riotgames.com/lol/match/v3/matches/' + matchData.matchID[indexIter] + '?api_key=' + API_KEY;
    async.waterfall([
        function (callback) {
            request(individualMatchURL, function (err, response, body) {
                // always trigger the callback even when you have errors or else your program will hang
                if (err)
                    return callback(err);
                if (response.statusCode != 200)
                    return callback(new Error('Status code was ' + response.statusCode));

                var json = JSON.parse(body);
                for (var j = 0; j < 10; j++) {
                    if (matchData.championID[indexIter] == json['participants'][j].championId) {
                        // match found: send back data
                        console.log('inside', json['participants'][j]);
                        return callback(null, json['participants'][j]);
                    }
                }
                // if it reaches this point, no match was found
                callback();
            });
        }
    ], callback); // note: this outer 'callback' is NOT the same as the inner 'callback'
}

然后当您调用函数时,例如

getIndividualMatchJSONObjHelper(data, participants, indexIter, function (err, json) {
     // you can only get the JSON at this point
     console.log('outside', json);
     matchParticipantData.specificParticipantData[i] = json;
});