我的代码旨在循环运动队ID的数组,以使用它们从API编译各种信息,然后将HTML添加到我的页面以显示每个队最近完成的比赛。它正在运行并且看起来很棒,除了:每次刷新时,结果都会以随机顺序出现在我的页面上。我认为这与循环快速移至下一个迭代有关,而服务器的响应会在随机时间返回。我希望结果首先是“爱国者”,然后是“ Steelers”,但结果是随机的,爱国者队几乎从来没有出现过。
此外,我对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);
})
};