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
相关产品推荐
相关产品推荐

