1

When I instance a class1 in another class2, I couldn't retrieve the value of a class attribute which contains the result of the async method which is already called in the constructor of the first class (DbHelper).

Here is the sample

class1

export class DbHelper{

  db: any;
  constructor() {
      this.createIndexDBStore();
  }

  //Init IndexDB store
  async createIndexDBStore() {
      this.db = await doSomething(...);
  }

  getDB() {
      return this.db;
  }
}

class2

export class test {
 const dbHelper= new DbHelper();
 const db = dbHelper.getDB(); // here the db is undefined
}

But when I return a string instead of the doSomething, the db variable will contain that string.

Heni
  • 156
  • 3
  • 12
  • You're calling `getDB` while `createIndexDBStore` is sleeping while it `await`s. It won't wake up and assign a value to `this.db` until the promise resolves. – Quentin Feb 05 '20 at 09:16
  • [Don't do that](https://stackoverflow.com/questions/24398699/is-it-bad-practice-to-have-a-constructor-function-return-a-promise). – Bergi Feb 05 '20 at 11:25

0 Answers0