async函数中用await触发SyntaxError,报错中top level bodies of modules是什么含义?
「top level bodies of modules」含义
这个表述指的是ES模块的顶层作用域,对应的是顶层await特性:
- 当你的JS文件以ES模块规范加载时(浏览器端给
<script>标签加type="module"属性、Node.js环境使用.mjs后缀或者在package.json中配置"type": "module"),可以直接在代码最外层(没有被任何函数包裹的层级)使用await关键字,不需要再额外包裹一层async函数。 - 非模块的普通脚本、CommonJS规范的JS环境不支持该特性。
你代码报错的实际原因
你现在的报错和顶层模块作用域没有关系,问题出在异步函数内部的遍历逻辑:
虽然外层的inputEntriesNotOnScreen是async函数,但你调用notFoundInInitialSearch.forEach时传入的是普通匿名回调函数,这个回调没有被async修饰,你在这个普通函数内部写await asyncCall()不符合语法规则,才会抛出该错误。
另外就算你给forEach的回调加上async,也会出现逻辑问题:forEach不会等待异步操作执行完成,会直接遍历完所有元素,达不到你要顺序执行异步逻辑的预期。
修复代码
把forEach替换为普通for循环即可:
function resolve1MS() { return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 1); }); } async function asyncCall() { let clicked = false; while( !clicked){ await resolve1MS(); if($('.ui-menu-item').length != 0){ $('.ui-menu-item')[0].click(); clicked = true; $matrix = $("table.timesheet tbody tr"); return { lastRow: $matrix.last() } } } } async function inputEntriesNotOnScreen($matrix, notFoundInInitialSearch){ let lastRow = undefined; // 替换forEach为for循环 for (let index = 0; index < notFoundInInitialSearch.length; index++) { const item = notFoundInInitialSearch[index]; console.log(item, index); if( lastRow == undefined){ lastRow = $matrix.last(); } else{ lastRow = await asyncCall(); } lastRow.find('.search')[0].click(); let $searchBar = $('.ui-autocomplete-input'); $($searchBar[index]).val(item[0][0]); $searchBar[index].dispatchEvent(new Event('input')); } }
内容的提问来源于stack exchange,提问作者Dillon V
相关产品推荐
相关产品推荐

