【发布时间】:2019-07-07 11:57:25
【问题描述】:
我有一个 Vue 应用程序,它有时会调用体育提要 API 端点来获取一系列游戏 ID,这样我就可以遍历 ID 来获取单个游戏的得分。所以首先在我做的主应用程序中:
// vue.js
/* jshint ignore:start */
axios
.get(
`https://api.mysportsfeeds.com/v1.2/pull/nba/${seasonName}/scoreboard.json?fordate=${
date.yesterday
}`,
config
)
.then(async response => {
this.sports_feeds_data = await response.data.scoreboard.gameScore;
return this.sports_feeds_data;
})
.then(async 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;
})
.then(response => {
this.sports_feeds_boxscores = getBoxScores(response);
})
.catch(error => {
console.log(error);
this.errored = true;
});
/* jshint ignore:end */
console.log("Here are boxScores" + this.sports_feeds_boxscores);================================================================================= //
// ============================ End Get NBA Scores ================================= //
// ================================================================================= //
现在在 getBoxScores.js 中,我想创建一个 promise 数组,然后通过 axios.all(promises) 一次将它们履行到 boxscores 数组中,并将其返回给 Vue.js 以进行进一步处理。它看起来像这样:
// getBoxScores.js
const axios = require("axios");
let boxScores = [];
let promises = [];
/* jshint ignore:start */
const getBoxScores = gameIDs => {
console.log(gameIDs);
gameIDs.forEach(function(item) {
console.log(item); // nothing output
console.log("Im in forEach"); // nothing output
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
}
})
);
});
console.log(promises);
axios.all(promises).then(function(results) {
results.forEach(function(response) {
boxScores.push(response.data.gameboxscore);
});
return boxScores;
});
};
/* jshint ignore:end */
module.exports = getBoxScores;
问题: 更新:查看 promises[] ok 但 this.sports_feeds_boxscores 在 getBoxScores(response) 返回时仍显示为空。有任何想法吗?谢谢。
【问题讨论】:
-
"I then call the function" :重要的是查看 one 脚本中的所有代码,以准确了解此类短语的含义.但请提供重现问题所需的最少代码。
-
根据请求更新代码。
-
因为 `gameIDs` 是异步获取的,并且您在完成之前进行了调用。 boxScores(gameIDs);` 调用应该在设置
gameIDs循环之后
标签: javascript promise async-await axios