0

Given the following code:

  async #token() {
    const value = await this.belcorp.getAccessToken();
    console.log(value);
  }

This code returns: enter image description here

But if I try to return that same result in my constructor with this code:

constructor() {
    const token = this.#token();
    console.log(token);
  }

  async #token() {
    return await this.belcorp.getAccessToken();
  }

returns the following: enter image description here

What should I do to retrieve only the previous object?

Luis
  • 2,006
  • 5
  • 31
  • 47
  • 7
    `async` functions return Promise instances; that's the whole point. – Pointy May 07 '20 at 17:59
  • 3
    Using `Promise`s in constructors is bad practice: [Is it bad practice to have a constructor function return a Promise?](https://stackoverflow.com/questions/24398699/is-it-bad-practice-to-have-a-constructor-function-return-a-promise) – Daemon Beast May 07 '20 at 18:01
  • Thanks for the reply, how should I do it? I do not have much experience. – Luis May 07 '20 at 18:04

2 Answers2

0

Aside from the issue of Promises in constructors, your code returns a Promise because that is what you told it to do: async functions return Promises. If you want the awaited Promise result instead, change the line to

const token = await this.#token();

Of course, you would need your constructor to be async in this case, so you will need to move your code outside your constructor.

Ashley
  • 897
  • 1
  • 5
  • 17
  • 1
    That's what I was trying to get at with the first part (issue of Promises in constructors), but clarified below. – Ashley May 07 '20 at 18:41
0

You cannot make a class constructor async. Instead, just make your own static constructor method -

class MyThing {
  constructor(token) { // cannot be async
    this.token = token // make sync instead
  }

  static async token() { // make static
    return new Promise(r =>
      setTimeout(r, 1000, "tkn123") // demo token response
    )
  }
  
  static async new () { // make async constructor
    return new MyThing(await this.token()) // await token
  }
}

const main = async () =>
{ console.log("loading...")
  const x = await MyThing.new() // <-- MyThing.new()
  console.log("got token:", x.token)
  return "done"
}

main().then(console.log, console.error)
// loading...
// got token: tkn123
// done
Mulan
  • 129,518
  • 31
  • 228
  • 259