Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

311
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda