3

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
}
9
  • 1
    const { x } = await a Commented Nov 6, 2021 at 11:44
  • 1
    @DimaParzhitsky, I think it will return a Promise since it is waiting for a, not for a.x. Commented Nov 6, 2021 at 12:15
  • Okay, got it. Don't judge me, people often confuse await a.x and (await a).x Commented Nov 6, 2021 at 15:07
  • 1
    I'm afraid, there's no such syntax in JavaScript yet, you have to do const x = await a.x Commented Nov 6, 2021 at 15:08
  • 1
    No, there is not. Also it's weird to have getters that return promises (that are usually involved in side effects), what is your actual use case? Commented Nov 6, 2021 at 22:11

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.