【发布时间】:2021-12-20 02:59:41
【问题描述】:
有没有办法在 JavaScript/TypeScript 中通过解构获取 async 属性?
像这样:
class A {
public get x() {
return this.getX()
}
private async getX() {
return 5
}
}
async function f(a : A) {
const { x } = a
console.log(x) // Promise
}
async function g(a : A) {
// works as const x = await a.x
const { await x } = a
console.log(x) // 5
}
【问题讨论】:
-
const { x } = await a -
@DimaParzhitsky,我认为它会返回一个
Promise,因为它正在等待a,而不是a.x。 -
好的,知道了。不要评判我,人们经常混淆
await a.x和(await a).x -
恐怕JavaScript中还没有这样的语法,你必须这样做
const x = await a.x -
不,没有。此外,让 getter 返回承诺(通常涉及副作用)也很奇怪,您的实际用例是什么?
标签: javascript typescript async-await destructuring