Javascript 为多个get请求创建承诺数组
我有一个Vue应用程序,在某一点上调用sports feeds API端点以获取一系列游戏ID,这样我就可以通过ID进行迭代以获取单个游戏的方块分数。因此,首先在主应用程序中,我会:Javascript 为多个get请求创建承诺数组,javascript,promise,async-await,axios,Javascript,Promise,Async Await,Axios,我有一个Vue应用程序,在某一点上调用sports feeds API端点以获取一系列游戏ID,这样我就可以通过ID进行迭代以获取单个游戏的方块分数。因此,首先在主应用程序中,我会: // vue.js /* jshint ignore:start */ axios .get( `https://api.mysportsfeeds.com/v1.2/pull/nba/${seasonName}/scoreboard.json?fordate=
// 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中,我想创建一个承诺数组,然后通过axios.allpromises将它们一次一个地实现到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;
axios.get(url, config)
.then(async response => { .... })
.then(async response => {
....
return gameIDs; // <-- better practice to drive the output through the chain
})
.then(boxScores); // <-- call it asynchronously!
.catch(error => { ... });
// Whatever code comes here should not expect anything from the above
// asynchronously retrieved data. It will not yet have been retrieved
问题:
更新:请参阅Promissions[]ok,但此.sports\u feeds\u boxscores返回时,分数仍显示为空。有什么想法吗?谢谢。当您异步检索数据时,您需要继续使用异步模式,而不是退回到同步序列 例如,您在启动异步请求获取游戏ID后立即同步访问游戏ID,因此这将不起作用:在执行BoxScoresGameID时;阵列游戏ID尚未填充 因此,您的代码应按如下方式组织:
// 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;
axios.get(url, config)
.then(async response => { .... })
.then(async response => {
....
return gameIDs; // <-- better practice to drive the output through the chain
})
.then(boxScores); // <-- call it asynchronously!
.catch(error => { ... });
// Whatever code comes here should not expect anything from the above
// asynchronously retrieved data. It will not yet have been retrieved
小心使用console.log:它可能会给人一种错误的印象,即在创建日志时,您的数据存在于阵列中。这不一定是真的:控制台稍后会在您在控制台中展开数组时检索内容。它并不总是反映日志创建时的情况。然后我调用该函数:重要的是在一个脚本中查看所有代码,以准确地了解这样的短语的含义。但请提供重现问题所需的最少代码。每个请求都会更新代码。因为“GameID”是异步获取的,并且您在调用完成之前进行了调用。boxScoresgameIDs;`调用应该在设置GameID的循环之后