Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda