Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 789
bool3max Avatar asked Nov 30 '16 16:11

bool3max


People also ask

How do I get await value?

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 .

How do you await in JavaScript?

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.

Does await return a promise or a value?

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.

How do I return async await promise?

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.


1 Answers

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.

like image 131
Michał Perłakowski Avatar answered Sep 21 '22 17:09

Michał Perłakowski