Reputation: 142
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?
Upvotes: 3
Views: 38
Reputation: 25392
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();
Upvotes: 2