【问题标题】:Unable to store JSON in a variable无法将 JSON 存储在变量中
【发布时间】:2017-08-05 09:49:07
【问题描述】:

我无法将 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); 

}

【问题讨论】:

    标签: json node.js async.js


    【解决方案1】:

    在您的 getIndividualMatchJSONObj 中

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

    json 到你的对象的设置是异步发生的,所以你的 json 在返回 matchParticipantData 后被接收和设置。

    您需要以某种方式暂停返回,直到 json 函数完成或将函数转换为使用回调来处理/使用数据而不是返回数据。

    正常:

    function test() {
        return "test";
    }
    

    用法:

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

    回调:

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

    用法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      相关资源
      最近更新 更多