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?
log(await getData()); })(); to create the getData function that returns the resolve value of the promise returned by axios. get . We then use await with getData to get the resolve value of the promise that was returned with return in getData .
The keyword await before a function makes the function wait for a promise: let value = await promise; The await keyword can only be used inside an async function.
Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
The behavior of async / await is similar to combining generators and promises. Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With