无法将 JSON 存储在变量中

Unable to store JSON in a variable

我无法将 JSON 存储在变量中。当我调用 getIndividualMatchJSONObjHelper 函数时,json 变量本身会打印出来,但在变量外部不存储任何内容。如何在 matchParticipantData.specificParticipantData 中正确存储 JSON 变量?

function getIndividualMatchJSONObj(matchData) {
   var matchParticipantData = {
        specificParticipantData: [numberOfGames]
    };

    for (var i = 0; i < numberOfGames; i++) {
       getIndividualMatchJSONObjHelper(matchData, matchParticipantData, i, function(err, json) {
            matchParticipantData.specificParticipantData[i] = json;
   });
} 
    return matchParticipantData;

}

function getIndividualMatchJSONObjHelper(matchData, matchParticipantData, indexIter, callback) {
    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)
                    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) {
                        return callback(null, json['participants'][j]);
                }
            }
        });
    }
], callback); 

}

在你的 getIndividualMatchJSONObj

for (var i = 0; i < numberOfGames; i++) {
       getIndividualMatchJSONObjHelper(matchData, matchParticipantData, i, function(err, json) {
            matchParticipantData.specificParticipantData[i] = json;
       });
} 
return matchParticipantData;

您的对象的 json 设置是异步发生的,因此您的 json 在 returning matchParticipantData 之后被接收和设置。

您需要以某种方式暂停 return 直到 json 函数完成,或者将函数转换为使用回调 handle/use 数据而不是 returning 数据。

正常:

function test() {
    return "test";
}

用法:

var data = test();
console.log(data);

回调:

function test(callback) {
    callback("test");
}

用法:

test(function(data) {
    console.log(data);
});