JavaScript循环调用Fetch API时async/await语法错误求助
问题解决:循环调用Fetch API时的await语法错误
错误原因
你遇到的SyntaxError: await is only valid in async functions, async generators and modules错误,核心原因是在forEach的普通回调函数里使用了await。forEach的回调并非异步函数,即便外层listarSchedules标记为async,也无法在内部的同步回调中直接使用await。
修复方案
提供两种实用修复方式,可按需选择:
方案1:使用for...of循环(顺序执行请求)
将forEach替换为for...of循环,即可在循环体内直接使用await,保证请求按顺序执行:
async function listarSchedules() { let allUserData = []; // 用for...of替代forEach,支持直接使用await for (const item of projetosList) { let projetoId = item.split("#")[0]; let projetoNome = item.split("#")[1]; console.log("PROJETO ID: " + projetoId + " PROJETO NOME: " + projetoNome); let urlSchedule = "https://gitlab.com/api/v4/projects/" + projetoId + "/pipeline_schedules?private_token=glpat-uSjCXDMEZPh5x6fChMxs"; console.log("urlSchedule"); console.log(urlSchedule); // 直接await请求结果,无需嵌套then const data = await getData(urlSchedule); let str = projetoId + "#" + data.description + "#" + data.owner.username; allUserData.push(str); } imprimirSchedule(allUserData); }
方案2:使用Promise.all并行执行请求(效率更高)
如果无需严格按顺序发起请求,推荐此方式,所有请求同时触发,大幅提升执行效率:
async function listarSchedules() { // 用map将每个item转换为异步Promise const allPromises = projetosList.map(async (item) => { let projetoId = item.split("#")[0]; let projetoNome = item.split("#")[1]; console.log("PROJETO ID: " + projetoId + " PROJETO NOME: " + projetoNome); let urlSchedule = "https://gitlab.com/api/v4/projects/" + projetoId + "/pipeline_schedules?private_token=glpat-uSjCXDMEZPh5x6fChMxs"; console.log("urlSchedule"); console.log(urlSchedule); const data = await getData(urlSchedule); return projetoId + "#" + data.description + "#" + data.owner.username; }); // 等待所有Promise完成,获取结果数组 const allUserData = await Promise.all(allPromises); imprimirSchedule(allUserData); }
额外优化建议
- 简化
getData函数:无需手动包裹Promise,fetch本身已返回Promisefunction getData(url) { return fetch(url).then(resp => resp.json()); } - 调整函数调用时机:
listarMeusProjetos是异步操作,直接调用listarSchedules可能导致projetosList为空,需等前者执行完成后再调用:async function listarMeusProjetos() { let meuId = 123456; let urlMeusProjetos = "https://gitlab.com/api/v4/users/" + meuId + "/projects?private_token=glpat-xx"; const allUserData = await getData(urlMeusProjetos); imprimirProjetos([allUserData]); // 匹配原逻辑的数组格式 } // 按顺序执行两个异步函数 listarMeusProjetos().then(() => { listarSchedules().then(() => console.log("DONE")); });
内容的提问来源于stack exchange,提问作者walves
相关产品推荐
相关产品推荐

