Accessing the await-ed value inline (JS)?

南楼画角 提交于 2020-01-03 19:14:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!