我有这个应用程序,可以调用API并从返回的对象中提取游戏ID。
/* jshint ignore:start */
axios
.get(
`https://api.mysportsfeeds.com/v1.2/pull/nba/${seasonName}/scoreboard.json?fordate=${
date.yesterday
}`,
config
)
.then(response => {
this.sports_feeds_data = response.data.scoreboard.gameScore;
return this.sports_feeds_data;
})
.then(response => {
// Fill up array with all the game ID's for today's games
// This will be used to retrieve the Box Scores later
response.forEach(function(item, index) {
gameIDs[index] = item.game.ID;
});
return gameIDs;
})
// Now call getBoxScores to retrieve box scores
.then(gameIDs => {
test = getBoxScores(gameIDs); // **No value returned**
console.log(test);
})
.catch(error => {
console.log(error);
this.errored = true;
});
/* jshint ignore:end */
现在,我们进入getBoxScores并获取boxScores:
let boxScores = [];
let promises = [];
/* jshint ignore:start */
const getBoxScores = gameIDs => {
gameIDs.forEach(function(item) {
let myUrl = `https://api.mysportsfeeds.com/v1.2/pull/nba/2018-2019-regular/game_boxscore.json?gameid=${item}`;
promises.push(
axios({
method: "get",
headers: {
Authorization:
"Basic NzAxMzNkMmEtNzVmMi00MjdiLWI5ZDYtOTgyZTFhOnNwb3J0c2ZlZWRzMjAxOA=="
},
url: myUrl,
params: {
teamstats: "none",
playerstats: "PTS,AST,REB,3PM",
sort: "stats.PTS.D",
limit: 3,
force: true
}
})
);
});
axios
.all(promises)
.then(function(results) {
results.forEach(function(response) {
boxScores.push(response.data.gameboxscore);
});
return boxScores;
})
.then(function(boxScores) {
console.log(boxScores);
return boxScores;
});
};
/* jshint ignore:end */
module.exports = getBoxScores;
问题: 1.无法将boxScores数组从getBoxScores.js返回。
更新的分辨率:
.then(async gameIDs => {
// Check if boxscores have been retrieved on previous tab click
this.sports_feeds_boxscores.nba =
this.sports_feeds_boxscores.nba || (await getBoxScores(gameIDs));
})
在getBoxScores中:
// axios.all returns a single Promise that resolves when all of the promises passed
// as an iterable have resolved. This single promise, when resolved, is passed to the
// "then" and into the "values" parameter.
await axios.all(promises).then(function(values) {
boxScores = values;
});
return boxScores;
};
module.exports = getBoxScores;
以上更新现已生效...