[英]How to wait for function to finish in javascript?
如何在 JavaScript 中等待 function 完成? 我有 2 個函數updateSeason
和updateFixtures
,我想等待第一個函數完成后再運行下一個函數。
我的兩個函數都是異步的,它們工作得很好。 唯一的問題是,如果我不使用setTimeout
,我需要運行它兩次,因為updateFixture
在updateSeason
完成之前運行,並且在第一次運行時仍然沒有要獲取的文件。
更新數據
const updateData = async () => {
await updateSeason();
await updateFixtures();
};
更新季節
// UPDATE SEASON
const updateSeason = async () => {
// SEASONS TEMPLATE
let seasonsTemplate = {
timestamp: new Date(),
season: null,
leagues: [],
};
// FETCH LEAGUES INFO
const leagues = await fetch(url + "leagues?subscribed=true&" + key)
.then((response) => response.json())
.then((data) => data.data);
// MAP THROUGH LEAGUES
leagues.map(async (league) => {
const id = `${league.league_id}&`;
// FETCH SEASONS INFO
const seasons = await fetch(url + "seasons?league_id=" + id + key)
.then((response) => response.json())
.then((data) => data.data);
// MAP THROUGH LEAGUES & POPULATE SEASONS TEMPLATE
seasons.map((season) => {
if (season.is_current) {
seasonsTemplate.season = `${moment(season.start_date).format("YYYY")}_${moment(season.end_date).format("YYYY")}`;
seasonsTemplate.leagues.push({
country_id: season.country_id,
league_id: league.league_id,
league_name: league.name,
season_id: season.season_id,
start_date: season.start_date,
end_date: season.end_date,
});
}
});
// CHECK / CREATE SEASON FOLDER
const currentSeasonFolder = `./data/${seasonsTemplate.season}`;
if (!existsSync(currentSeasonFolder)) {
await mkdir(currentSeasonFolder);
await mkdir(`${currentSeasonFolder}/matches`);
}
// CREATE / UPDATE SEASON FILES
await writeFile("./data/current_season.json", JSON.stringify(seasonsTemplate));
await writeFile(`${currentSeasonFolder}/season.json`, JSON.stringify(seasonsTemplate));
console.log(`${league.name} updated...`);
});
};
更新夾具
// UPDATE FIXTURES
const updateFixtures = async () => {
// FIXTURES TEMPLATE
let fixturesTemplate = {
timestamp: new Date(),
season: null,
fixtures: [],
};
// FETCH CURRENT SEASON INFO
const season = await fetch(api + "current_season.json").then((response) => response.json());
// POPULATE FIXTURES TEMPLATE SEASON
fixturesTemplate.season = season.season;
// MAP THROUGH LEAGUES
season.leagues.map(async (league) => {
const id = `${league.season_id}&`;
// FETCH COMPETITION FIXTURES
const fixtures = await fetch(url + "matches?season_id=" + id + key)
.then((response) => response.json())
.then((data) => data.data);
// MAP THROUGH FIXTURES & POPULATE FIXTURES TEMPLATE
fixtures.map((match) => {
if ((match.home_team.team_id === teamId || match.away_team.team_id === teamId) && match.status !== "postponed") {
fixturesTemplate.fixtures.push({
match_timestamp: new Date(match.match_start_iso).getTime(),
match_start: match.match_start_iso,
match_id: match.match_id,
status: match.status === "" ? "notstarted" : match.status,
home_team: getTeamName(match.home_team.team_id),
home_short: getShortName(match.home_team.team_id),
away_team: getTeamName(match.away_team.team_id),
away_short: getShortName(match.away_team.team_id),
});
}
});
// SORT FIXTURES BY DATE IN ASCENDING ORDER
fixturesTemplate.fixtures.sort((a, b) => a.match_timestamp - b.match_timestamp);
// CREATE / UPDATE FIXTURES FILES
const currentSeasonFolder = `./data/${season.season}`;
await writeFile(currentSeasonFolder + "/fixtures.json", JSON.stringify(fixturesTemplate));
console.log("Fixtures updated...");
});
};
更新:
問題在於函數本身。 async Array.prototype.map
在updateSeason
和updateFixtures
函數中都替換for
循環,現在正在工作
為什么不只是,
async function updateData() {
await updatedSeason();
await updateFixtures()
}
updateData();
即使您不能在異步 function 之外使用“await”關鍵字,您也可以只對定義的函數使用 async/await。
因此,例如,您有一個 index.js 文件,您可以執行以下操作:
async function main() {
await updateSeason();
await updateFixtures();
}
main()
或使用縮寫形式直接調用 function
(async function main() {
await updateSeason();
await updateFixtures();
})()
無論如何,避免在異步 function 中使用“writeFileSync”或其他“同步”函數,因為這會阻塞事件循環並降低性能。
編輯:我現在看到您正在使用帶有異步回調的 Array.prototype.map function,這可能是問題所在。
試試看這里: https://flaviocopes.com/javascript-async-await-array-map/
或者,否則,使用標准 for 循環來處理您的聯賽
您忘了在 function 之前加上“等待”
const updateData = async () => {
// Add await before the functions because they are async functions
await updateSeason()
await updateFixtures()
};
Async Await 可以在這里為您提供幫助,因為它們都是異步函數。
const updateData = async () => {
await updateSeason();
await updateFixtures();
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.