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

312
Visualizações
Trying to use await in Javascript but it's returning error

I don't know what is wrong with this code. It throws an error in the console that says :

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

Can anyone tell me what's wrong with my usage of await?

let user = {
    name: 'George',
    surname: 'Arqael'
};

let regUser = await fetch(url, {
    method: 'post',
    headers: {
        'Content-type': 'application/json; charset=utf-8'
    },
    body: JSON.stringify(user)
});

let result = await regUser.json();
console.log(result);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Await requires async. You should be able to wrap it in an async function.

async function f() {
  let regUser = await fetch(url, {
    method: 'post',
    headers: {
      'Content-type': 'application/json; charset=utf-8'
    },
    body: JSON.stringify(user)
    });
    
  let result = await regUser.json();
  console.log(result);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

As the error says, top-level await is only available in modules. If you add type="module" to your script tag it will work as expected.

<script type="module">
  let user = {
      name: 'George',
      surname: 'Arqael'
  };

  let regUser = await fetch(url, {
      method: 'post',
      headers: {
          'Content-type': 'application/json; charset=utf-8'
      },
      body: JSON.stringify(user)
  });

  let result = await regUser.json();
  console.log(result);
</script>

Or, wrap your code in an async function as MortBort suggested.

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