[Vuejs]-Resolving async value from JS class

0👍

Looks like you are not awaiting your getToken result in the profile constructor. Problem is, constructors are always synchronous. So in order to await the token, you need to do something like make Profile#auth0manage an async value and await that. Maybe like:

export default class Profile {
  constructor () {
    let token = new Token()
    this.auth0Manage = new Promise((resolve, reject) => {
      token.getToken().then((result) => {
        return new auth0.Management({
          domain: '.auth0.com',
          token: `${result}`
        })
      }).then(resolve, reject)
    })
  }

  async getProfile () {
    let auth0Manage = await this.auth0Manage
    return new Promise((resolve, reject) => {
      let idToken = localStorage.getItem('id_token')
      let decoded = jwt_decode(idToken)
      let userId = decoded.sub
      auth0Manage.getUser(userId, function (err, data) {
        if (err) {
          console.error(err)
        }
        resolve(data)
      })
    })
  }
}

Caveats of this are that if you get an error in getToken then every call to getProfile will return the same error. So you may want to handle that somehow. Also, you have to remember to await every use of this.auth0Manage. Ideally, you could do something like pass in the auth0Manager to the constructor of Profile, so that you won’t event try to make a profile until the token has been fetched. Tends to work out better to do things that way.

Leave a comment