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

193
Visualizações
await in different positions yielding different results

I'm trying to hide the latency of some code that does calculations.

Examples below. In the first case below, I get the expected answer:

async function calculateStuff(thing) {
    //do stuff here
    return {"a": a, "b": b, "c": c};
}
const data = await calculateStuff(obj); //takes a while
const first = data["a"] //valid data
const second = data["b"] //valid data
const third = data["c"] //valid data

I'd like to hide the latency of calculateStuff by doing either of the following, but both methods have my variables become undefined instead:

async function calculateStuff(thing) {
    //do stuff here
    return {"a": a, "b": b, "c": c};
}
data = calculateStuff(obj); //takes a while
//...other calculations here...
await data;
const first = data["a"] //undefined
const second = data["b"] //undefined
const third = data["c"] //undefined

Likewise:

async function calculateStuff(thing) {
    //do stuff here
    return {"a": a, "b": b, "c": c};
}
data = calculateStuff(obj); //takes a while
//...other calculations here...
const first = await data["a"] //undefined
const second = await data["b"] //undefined
const third = await data["c"] //undefined

What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

An async function will return a Promise. Calling await myAsyncFunction(), will return the value of the Promise once the Promise is fulfilled. Note the return in the previous statement. It does not change the pointer in place.

E.g. calling await data does not change data.

You can get the output you expect by calling data = await data.

async function test()
{
  return {a: 1, b: 2};
}

async function run()
{
  let data = test();
  data = await data;
  console.log("A", data.a);
}

run();

You can also use .then().

async function test()
{
  return {a: 1, b: 2};
}

async function run()
{
  let data = test();
  data.then((out) => {
    console.log("A", out.a);
  });
}

run();

about 4 years ago · Juan Pablo Isaza Relatório
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