【问题标题】:Top level bodies of modules syntax error with async/await带有异步/等待的模块语法错误的顶级正文
【发布时间】:2021-10-18 18:31:39
【问题描述】:

我的await for asyncCall()inputEntriesNotOnScreen 函数中完成,尽管它在异步函数中,但它不起作用。我收到此错误:

未捕获的语法错误: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'));
  });
}

【问题讨论】:

  • 你怎么打电话给inputEntriesNotOnScreen
  • 您正在为非异步的 forEach 创建一个内部函数。将 forEach 替换为 for 循环。
  • 指的是 ES2015 Module 语法。从技术上讲,您可以在模块的顶层使用await,而不必编写异步函数。见the proposal that made it happen。它将包含在 ES2022 中。
  • @AlbertoRivera 谢谢我很困惑,忘记了我实际上是在创建另一个函数!

标签: javascript asynchronous async-await


【解决方案1】:

您正在创建一个函数来传递给您的forEach,而不是async

forEach 替换为标准的for 循环应该允许您根据需要使用await

提醒一下,如果你在forEach 中使函数异步,比如forEach(async function(item, index),你将能够在函数内部使用await,但所有的回调将并行运行(到达后await),你将无法等待它们。

https://jsfiddle.net/8nwdus0h/

更多信息可以阅读Using async/await with a forEach loop

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 2022-01-04
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多