【发布时间】:2019-11-24 23:20:10
【问题描述】:
我的代码旨在循环遍历一组运动队 ID,以使用它们从 API 编译各种信息,然后将 HTML 添加到我的页面以显示每支球队最近完成的比赛。它正在工作并且看起来很棒,除了:每次刷新时结果都会以随机顺序出现在我的页面上。我认为这与循环快速移动到下一次迭代有关,而来自服务器的响应是随机返回的。我希望结果首先是“Patriots”,然后是“Steelers”等,但结果是随机的,Patriots 几乎不会排在第一位。
另外,我对 JS 很陌生,所以我确信我可以做很多事情来使它变得更好,所以提前谢谢你!
//Define the teams I want scores from and their API reference numbers.
let teams = new Map();
teams.set("Patriots", 134920);
teams.set("Steelers", 134925);
teams.set("Bruins", 134830);
teams.set("Penguins", 134844);
teams.set("Celtics", 134860);
teams.set("Red Sox", 135252);
teams.set("Huskers", 136923);
let teamArr = Array.from(teams.values());
for (i = 0; i < teamArr.length; i++) {
console.log(teamArr[i]);
}
//Get the team data so that we can pull the logo image.
async function getTeamData(teamID) {
let result = await fetch(`https://www.thesportsdb.com/api/v1/json/1/lookupteam.php?id=${teamID}`)
let teamData = await result.json();
return teamData.teams[0];
}
//Get the info for the teams last game.
async function getLastGame(teamID) {
let result = await fetch(`https://www.thesportsdb.com/api/v1/json/1/eventslast.php?id=${teamID}`)
const lastGames = await result.json();
const lastGame = lastGames.results[0];
return lastGame;
};
//Populate the final scores with new HTML after pulling all the info from the API.
for (let i = 0; i < teamArr.length; i++) {
let homeTeam, awayTeam, homeTeamData, awayTeamData, homeTeamLogo, gameDay;
getLastGame(teamArr[i])
.then(lastGame => {
gameDay = lastGame.dateEvent;
homeTeam = {
name: lastGame.strHomeTeam,
id: lastGame.idHomeTeam,
score: lastGame.intHomeScore,
};
awayTeam = {
name: lastGame.strAwayTeam,
id: lastGame.idAwayTeam,
score: lastGame.intAwayScore
}; //This is all the info we need except for the team icons.
}).then(result => {
homeTeamData = getTeamData(homeTeam.id)
return homeTeamData;
}).then(result => {
homeTeam.logo = result.strTeamBadge;
}).then(() => {
awayTeamData = getTeamData(awayTeam.id)
return awayTeamData;
}).then(result => {
awayTeam.logo = result.strTeamBadge; //After getting who was home and who was away, these let us pull and put the right icon in the table.
}).then(() => {
let html = ` <tr>
<th><img src="%awayImg%" alt="Away" id="${i}-away" class="team-logo"></th>
<th><div class="at-vs">@</div></th>
<th><img src="%homeImg" alt="Home" id="${i}-home" class="team-logo"></th>
</tr>
<tr>
<th><div class="away-score">%awayScore%</div></th>
<th><div class="gameday">%gameDay%</div></th>
<th><div class="home-score">%homeScore%</div></th>
</tr>`;
let newhtml = html.replace(`%awayImg%`, awayTeam.logo + "/preview");
newhtml = newhtml.replace(`%homeImg`, homeTeam.logo + "/preview");
newhtml = newhtml.replace(`%awayScore%`, awayTeam.score);
newhtml = newhtml.replace(`%gameDay%`, gameDay);
newhtml = newhtml.replace(`%homeScore%`, homeTeam.score);
document.querySelector(`.past-games-table`).insertAdjacentHTML(`beforeend`, newhtml);
})
};
【问题讨论】:
标签: javascript api for-loop asynchronous promise