javascript - 从模块中的 Promise 调用返回值
问题描述
我有这个应用程序调用 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. 无法从 getBoxScores.js 返回 boxScores 数组。
- 当我进行 console.log 测试时,数组中什么也没有。控制台记录 boxScores 我看到我已解决的带有值的承诺。任何见解表示赞赏。谢谢...
更新的分辨率:
.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;
上述更新现在有效...