我在设置变量或至少在异步瀑布中返回它时遇到了问题。我知道你不能在异步中返回,但是我对我的变量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?
答案 0 :(得分: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;
});