问题
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?
回答1:
You need to wrap the await
keyword and the promise in parentheses, like that:
const value = (await Promise.resolve({a: 3})).a;
This way you're awaiting the promise and then accessing the a
property of the resolved value.
await(Promise.resolve({a: 3})).a
doesn't work, because await
is not a function, but an operator.
回答2:
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.
来源:https://stackoverflow.com/questions/40893232/accessing-the-await-ed-value-inline-js