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

234
Vistas
Issue regarding async functions - await is only valid in async functions

In a file called getData.js , I wrote the following code

module.exports = async function (page, id) {

  const options = {
    ...
  };

  axios
    .request(options)
    .then((response) => {
      myData = JSON.stringify(response.data);

      return myData;
    })
    .catch((error) => {
      console.error(error);
    });
};

Now in my main index.js file, I imported the above module then I have this snippet,

const server = http.createServer((req, res) => {
    res.writeHead(200, { "Content-Type": "application/json" });

    let finalData = await getData(myPage, myID);
    res.end(finalData);

});

When I run this node crashes and I get this error

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

How do I make my code to work? I thought of using async-await becuase response.data is very big, but clearly I don't understand async-await functions fully. In the external module, If I try to return myData outside the .then block and also don't use async-await, then I get undefined finalData.

about 4 years ago · Juan Pablo Isaza
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