1

I am wanting to use an object that is returned from an asynchronous function.

async function myPromise() {
  console.log("Single-line", await getUsers().quote);
  let users = await getUsers();
  console.log("Multi-line", users.quote);
}

async function getUsers() {
  return await new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({
        name: "Jeff",
        id: 1,
        quote: "Hello world!"
      });
    }, 1000)
  });
}

myPromise();

Why do I have to assign the result of an asynchronous function to a variable before I can use the properties stored within the object that was returned?

Liam Pillay
  • 592
  • 1
  • 4
  • 19

1 Answers1

2

The property accessor has precedence over the await operator, so you need to add parentheses:

(await getUsers()).quote
trincot
  • 317,000
  • 35
  • 244
  • 286