简体   繁体   English

Typescript继承和Promise:如何在子类中获取已解决的Promise

[英]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: 我有三个类,即基类AnimalCat子类以及App类:

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类调用Animal类来获取数据, Cat类应过滤数据并获取仅与Cat数据相关的数据。

App.ts App.ts

Resolves the promise and should get cats but gets undefined because the sub class is constructed before the promise is resolved; 解决了promise,应该得到cat,但是变得不确定,因为子类是在promise解决之前构造的;

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

Animal.ts Fetches Animal data Animal.ts获取动物数据

    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 Cat.ts getAnimalData是未定义的,因为基类didint完成获取

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. 当然,我可以实例动物类等到承诺解决然后实例里面的猫类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. 将promise的结果分配给变量并在其他地方访问它是危险的,因为您可能在promise解析之前访问了它,然后它不起作用。 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... 但是我根本不知道为什么你需要一堂课...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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