Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda