简体   繁体   中英

Typescript inheritance and promises: how to get resolved promise in the sub class

I have three classes the base class Animal and the Cat sub class and the App class:

The app class calls the Animal class which fetches the data, the Cat class should filter the data and get the data only relevant to the Cat data.

App.ts

Resolves the promise and should get cats but gets undefined because the sub class is constructed before the promise is resolved;

this._cats = new Cats();
this._cats.fetchAnimalData().then(() => {
     this._cats.getCats(); // returns undefined
});

Animal.ts Fetches Animal data

    private async _setAnimalsDataContract(): Promise<[]> {
        return await ...;
    }
    public getAnimalData() {
        return this._animalData;
    }
    public setAnimalData(data) {
        this._animalData = data;
    }
    public fetchAnimalData() : Promise<void> {
        return this._animalDataPromise
                .then((dataSet: IAnimal;[]) => {
                   this._setAnimalData(dataSet);
                }).catch(() => {
                    throw new Error('...');
                });
   }

Cat.ts getAnimalData is undefined because the base class didint finish fetching

export default class Cat extends Animal {
    constructor() {
       super();
       this._catData = (this._formatCatData(this.getAnimalData()));
    }
    getCats() {
       return this._catData;
    }
}

I could of course instantiate Animal class wait until promise is resolved then instantiate the Cat class inside then but it would not make sense to do class extension at all then.

How to get base class resolved promise data inside the sub class when its finished ?

Assigning the result of a promise to a variable and accessing it somewhere else is dangerous, as you might access it before the promise resolved and then it doesn't work. Instead just work with the promise:

 class Animal {
   get data() {
      return this._promise || (this._promise = fetchAnimalData());
   }
}

class Cat extends Animal {
 get cats() {
   return this.data.then(data => /*...*/);
 }
}

const cat = new Cat();
cat.cats.then(console.log);

But I don't know why you need a class at all...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM