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

191
Views
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 answers
Answer question

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 Report
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!