Search code examples
javascriptjavascript-objectses6-promise

Why can't I single-line object properties from objects returned from async functions?


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?


Solution

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

    (await getUsers()).quote