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.