Is there a way to get async properties with destructuring in JavaScript/TypeScript?
Like this:
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
}
If using utility function is allowed,
the following would work.
Its side effect is that the getters for all properties are executed.
const classToObject = async theClass => {
const originalClass = theClass || {}
const keys = Object.getOwnPropertyNames(Object.getPrototypeOf(originalClass))
let classAsObj = {}
for(const key of keys) {
classAsObj[key] = await originalClass[key]
}
return classAsObj
}
async function g(a : A) {
// works as const x = await a.x
const {x} = await classToObject(a);
console.log(x) // 5
}
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