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?
The property accessor has precedence over the await
operator, so you need to add parentheses:
(await getUsers()).quote