Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring async properties in JavaScript/TypeScript

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
}
like image 474
hopeless-programmer Avatar asked Jan 25 '26 02:01

hopeless-programmer


1 Answers

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
}
like image 71
hashed tomato Avatar answered Jan 26 '26 15:01

hashed tomato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!