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

async函数中出现unexpected reserved word 'await'语法错误如何解决

错误原因分析
  • await 关键字仅允许在 async函数的直接作用域 内使用。你虽将外层func声明为async类型,但所有await语句都写在map方法的普通回调函数里,该回调本身没有被标记为async,因此JS引擎直接抛出语法错误。
  • 额外优化提示:你当前用map但没有用到它的返回值,属于不必要的调用,如果只需要遍历执行操作可以替换为更合适的遍历写法。
修复方案

方案1:并行处理(性能更高,推荐大部分场景)

将map的回调声明为async,再通过Promise.all等待所有异步任务执行完成:

const func = async () => {
  await Promise.all(submission[0].emoticons.map(async (item, idx) => {
    console.log('apngToFrame is working')
    const imgsrc = `${url}${item.id}`
    var container2 = document.querySelector('.output2')
    const response = await fetch(imgsrc)
    const buffer = await response.arrayBuffer()
    const apng = parseAPNG(buffer)
    if (apng instanceof Error){
      console.error('apng.message', apng.message)
      return ;
    }
    await apng.createImages()
    apng.frames.forEach(f => {
      container2.appendChild(f.imageElement)
    })
  }))
}

方案2:串行处理(适用于需要控制并发、按顺序执行的场景)

改用for...of循环,不需要额外嵌套async回调,直接在外层async作用域内使用await:

const func = async () => {
  // 把公共DOM查询提出来避免循环内重复查询
  const container2 = document.querySelector('.output2')
  for (const item of submission[0].emoticons) {
    console.log('apngToFrame is working')
    const imgsrc = `${url}${item.id}`
    const response = await fetch(imgsrc)
    const buffer = await response.arrayBuffer()
    const apng = parseAPNG(buffer)
    if (apng instanceof Error){
      console.error('apng.message', apng.message)
      continue
    }
    await apng.createImages()
    apng.frames.forEach(f => {
      container2.appendChild(f.imageElement)
    })
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 20:21:02