2017-07-17 59 views
0

我在设置变量时遇到问题,或者至少在异步瀑布中返回它。我知道你不能以异步方式返回,但是我对我的变量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; 
} 

我该如何获得正确返回jsonFinal的函数?

回答

1

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

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; 
}); 
+0

感谢您的回复。但问题是,当我将它存储到一个变量中时,打印出来时我仍然未定义。你确定它回来了吗?这里是如何存储变量: 'matchParticipantData.specificParticipantData [i] = getIndividualMatchJSONObjHelper(matchData,matchParticipantData,i,function(err,json){});' –

+0

再次*您只能获取回调中的变量与任何异步操作*。你的函数不会返回任何东西,但它提供了一个回调函数,当它的异步操作完成时,它有一个参数'json'。检查了它。 – Mikey

+0

非常感谢!你帮助我更好地理解回调。但我只关心一件事。我注意到打印对象 'matchParticipantData.specificParticipantData [i]'不包含函数后面的json。我用一个变量在函数中进行了测试,但没有在其外部进行测试。是否有一个原因?当json被设置时,我需要它在函数的外部 –