JavaScript中已声明async函数仍触发await错误的解决方法
解决async函数内使用await仍报错的问题
你遇到的报错原因很明确:await写在了jQuery .each()的回调函数里,这个回调并没有声明为async,哪怕外层的Refresh函数是async,也管不到内部回调的作用域。
方案一:改用for循环(推荐,串行执行)
把.each()替换成普通的for循环,让await处于Refresh这个async函数的作用域内,这样就能正常生效,且元素会按顺序串行处理:
async function Refresh(regListResult) { const $dfxContents = $(".dfxContent"); // 遍历索引13到36(对应原逻辑的index >=13 && index <37) for (let index = 13; index < 37; index++) { const $content = $dfxContents.eq(index); const regComment = $content.nextAll().eq(4).html(); if (regComment.indexOf("1") !== -1) { const chnPlace = ChnPlaceGet(a, b, c); await new Promise(resolve => setTimeout(resolve, 1000)); const chnPlaceData = '两者应匹配,' + chnPlace; RefreshAnother(Data, index); $content.html(a + b + c); } } }
方案二:给.each()的回调加async(并行执行)
如果业务允许所有符合条件的元素并行处理,可以直接把.each()的回调声明为async函数,这样内部的await就能生效:
async function Refresh(regListResult) { $(".dfxContent").each(async function (index) { if (index >= 13 && index < 37) { const regComment = $(this).nextAll().eq(4).html(); if (regComment.indexOf("1") !== -1) { const chnPlace = ChnPlaceGet(a, b, c); await new Promise(resolve => setTimeout(resolve, 1000)); const chnPlaceData = '两者应匹配,' + chnPlace; RefreshAnother(Data, index); $(this).html(a + b + c); } } }); }
两种方案的区别
- 方案一的for循环是串行执行:每个元素的处理会等待上一个元素的
await完成后再开始,适合需要按顺序处理的场景。 - 方案二的async回调是并行执行:所有符合条件的元素会同时触发等待,不会互相阻塞,适合不需要顺序的场景。
内容的提问来源于stack exchange,提问作者xxwork
相关产品推荐
相关产品推荐

