-3

A global object has its key/value (thing) is set in an async function setter(); using await. How to asynchronously read the value of thing in another async function getter();?

I'm getting undefined error because the getter(); is running before the await in setter(); completes.

let obj = {};

async function af() {
    return 1;
}

(async function setter () {
  obj.thing = await af();
})();

(async function getter () {
  let thing = obj.thing;
})();
Steve
  • 4,946
  • 12
  • 45
  • 62

1 Answers1

-1

You should wait for setter function to finish, you're getting a race condition problem with this approach.

An example of how that would work would be:

var obj = {};

async function af() {
    return 1;
}

(async function() {
    await (async function setter () {
      obj.thing = await af();
    })();

    await (async function getter () {
      let thing = obj.thing;
    })();

    console.log(obj.thing);
})();

At the end of the function it should log 1 that is returned on af function

Elias Dal Ben
  • 429
  • 1
  • 3
  • 6