Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
Top level bodies of modules syntax error with async/await

My await for asyncCall() to finish in the inputEntriesNotOnScreen function does not work despite it being in an async function. I get this error:

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules

What does the second part of the error mean?

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'));
  });
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are creating a function to pass to your forEach which is not async.

Replacing the forEach with a standard for loop should allow you to use await as needed.

As a heads up, if you make the function in the forEach async, like forEach(async function(item, index), you will be able to use await inside the function, but all the callbacks will be ran in parallel (after reaching the await), and you won't have a way to wait for them.

https://jsfiddle.net/8nwdus0h/

For more information, you can read Using async/await with a forEach loop

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda