'how to access data outside promise .then [duplicate]

so I have class for data object, I'm trying to define one property where I fetch it's value from api

this is how the class looks like:

export default class User extends Base {
  ....
  constructor(packet: Packet) {
    ....
    this.card = this.get_user_card() // showing undefined
  }

  get_user_card(): Card {
    this.rest.api(...).get().then((res: any) => {
      console.log(res.data); //  return the card data
      return res.data;
    })
  }
}

it's showing undefined when I set to card properties outside the function

I even tried this but this one showing Promise <pending> I can't use await inside constructor

return this.rest.api(...).get().then((res: any) => {
  return res.data;
})

and this but it's showing undefined for both and if I make it asynchronous it will return promise pending for the this.card

const res = this.rest.api(...).get()
console.log(res.data) //undefined
return res.data; //undefined too

tried this one too and doesn't work

this.rest.api(...).get().then((res: any) => {
  this.channel = res.data; //not working
  // even assign
  Object.assign(this, { card: res.data }); //not either
})

but console logging inside their .then is working. can someone help me or have other solution?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source