Trying to solve my issue I raised in a different question that was closed as a duplicate even though I stated I had read the various other answers and was still struggling to work out what to do. An answer was provided that I couldn't get to work - which is why I'm now asking this.
Original question - Returning the value of an async axios API call to a variable
Basically I'm trying to assign a variable after it gets the data from an async function and I simply don't know how to do it.
I was told I could simply use a top level await but...
let myObject = await getSelfLink();
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
I was then told this was because I'm using an old version of node but...
$ node -v
v16.8.0
This is my entire .js file:
const http = require('http');
const axios = require('axios').default;
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(screenData);
});
server.listen(port, hostname, () => {
//console.log(`Server running at http://${hostname}:${port}/`);
});
const queryData = '123456';
const getLink = async () => {
try {
const resp = await axios.get(`https://www.apisite.com/{queryData}`);
return resp.data;
} catch (err) {
console.error(err);
}
};
let myObject = await getLink();
/*
(async () => {
let myObject = await getSelfLink();
})();
*/
console.log(myObject);
(As an aside, if I comment out the let myObject line and uncomment the final anonymous function block which I was advised to also use, it just claims that the myObject variable doesn't exist and if initialised first with let myObject = '' it just returns an empty line in console)