Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!