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

195
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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