0

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.

  • `(req, res) => { ... }` is not an async function so you can't use `await` within it. You can easily change it to `async (req, res) => { ... }`. Also, your `getData` does not need to be `async` and should `return` the Axios promise, aka `return axios.request(...` – Phil Dec 07 '21 at 23:22
  • Unrelated to the syntax error, the anonymous function in getData.js must return something. `return axios.request...` – danh Dec 07 '21 at 23:25

0 Answers0