You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

async函数内部使用await报仅可在async函数中使用错误如何解决

问题解决

报错原因

await关键字仅允许在标记为async的函数作用域内使用,你的代码存在两个核心问题:

  • 你把await fetch、await response.json写在了forEach的普通回调函数中,这个回调没有添加async标识
  • 即使给forEach回调加async,forEach本身也不支持异步迭代,会出现执行顺序错乱、异步操作未完成就进入下一轮循环的问题,不推荐使用

修复方案

首先建议不要混用async/await和then链式调用,两种语法选其一即可,代码可读性更高。以下提供两种可用的实现:

方案1:串行执行(适合请求量小、避免触发接口限流的场景)

async function mainThree() {
    // 直接用await获取省份查询结果
    const provinceList = await ProvinceList.find({});
    // 使用for...of遍历,支持内部await
    for (const province of provinceList) {
        console.log(province.id);
        const response = await fetch(`https://xxxx.com/api/getSubAddressList?addressId=${province.id}`, {
            "headers": {
                "accept": "application/json, text/plain, */*",
                "accept-language": "en-US,en;q=0.9,si;q=0.8",
                "cache-control": "no-cache",
            },
            "referrer": "https://www.xxxx.com/",
            "referrerPolicy": "strict-origin-when-cross-origin",
            "body": null,
            "method": "GET",
            "mode": "cors"
        });
        const datalist = await response.json();
        // 插入操作也添加await,避免未完成插入就结束执行
        await CityList.insertMany(datalist.module);
    }
}

方案2:并行执行(适合请求量不大、需要提升执行效率的场景)

async function mainThree() {
    const provinceList = await ProvinceList.find({});
    // 把每个省份的处理逻辑包装为独立Promise,用Promise.all并行执行
    const taskList = provinceList.map(async (province) => {
        console.log(province.id);
        const response = await fetch(`https://xxxx.com/api/getSubAddressList?addressId=${province.id}`, {
            "headers": {
                "accept": "application/json, text/plain, */*",
                "accept-language": "en-US,en;q=0.9,si;q=0.8",
                "cache-control": "no-cache",
            },
            "referrer": "https://www.xxxx.com/",
            "referrerPolicy": "strict-origin-when-cross-origin",
            "body": null,
            "method": "GET",
            "mode": "cors"
        });
        const datalist = await response.json();
        return CityList.insertMany(datalist.module);
    });
    // 等待所有请求和数据库插入操作完成
    await Promise.all(taskList);
}

注意事项

  • 所有异步操作都建议添加await确认执行完成,避免出现数据丢失、逻辑提前结束的问题
  • 并行执行效率更高,但请求量过大时可能触发目标接口的限流规则,可根据实际业务场景选择合适的方案

内容的提问来源于stack exchange,提问作者srinath madusanka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 05:48:02