Bogdan M. Bogdan M. - 9 days ago 6
Javascript Question

Accessing the await-ed value inline (JS)?

First I wrote something like this:

(async function() {
const value = await Promise.resolve({a: 3}).a
console.log(value)
})().catch(console.error);


But I quickly came to the conclusion that that's not going to work since we're gonna be awaiting the
a
property of what
Promise.resolve
returns, which is undefined.

So I tried to wrap my
await
call into parenthesis:

(async function() {
const value = await(Promise.resolve({a: 3})).a
console.log(value)
})().catch(console.error);


Which didn't work either. (it logs
undefined
)

So it seems the only way to extract the
a
prop is to do something like this:

(async function() {
const resolvedValue = await Promise.resolve({a: 3});
let aProp = resolvedValue['a'];
})().catch(console.error);


, which adds an unnecessary line of code.

I feed like this kinda defeats the purpose of async/await. Is this correct or am I missing something?

Answer

you need to await on a promise, not a property of one. JavaScript is going to expect a to be a promise, but its not.

await is an operator statement, not a function.