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

233
Visualizações
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 à 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