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

168
Views
How to use a top level await in node 16?

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)

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!