![](/img/trans.png)
[英]Getting this error "await is only valid in async functions and the top level bodies of modules" in chrome extension with async await
[英]Top level bodies of modules syntax error with async/await
盡管它在異步函數中,但我await
asyncCall()
在inputEntriesNotOnScreen
函數中完成不起作用。 我收到此錯誤:
未捕獲的 SyntaxError:await 僅在異步函數和模塊的頂級主體中有效
錯誤的第二部分是什么意思?
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;
notFoundInInitialSearch.forEach(function(item, 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');multiple times
$($searchBar[index]).val(item[0][0]);
$searchBar[index].dispatchEvent(new Event('input'));
});
}
您正在創建一個傳遞給您的forEach
的函數,該函數不是async
。
用標准for
循環替換forEach
應該允許您根據需要使用await
。
提醒一下,如果您在forEach
中使函數異步,例如forEach(async function(item, index)
,您將能夠在函數內使用await
,但所有回調將並行運行(到達等待),您將無法等待它們。
https://jsfiddle.net/8nwdus0h/
有關更多信息,您可以閱讀在 forEach 循環中使用 async/await
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.