【问题标题】:Code continues to execute without awaiting代码继续执行而不等待
【发布时间】:2020-06-14 19:41:28
【问题描述】:

我有这样的结构:

export class SomeDerived extends SomeBase implements OnInit{
    public async ngOnInit(): Promise<void> {
        await super.ngOnInit();
        this.getBy(this.x);
    } 
}

export class SomeBase implements OnInit {
    public x: any;
    public async ngOnInit(): Promise<void> {
        try{
            await this.fetch();
        }catch(e){}
    }

    public async fetch(): Promise<void> {
        const someId = await this.requestService.fetchId().toPromise().id;
       this.x = await this.requestService.fetchX(someId).toPromise();
    }
}

好吧,当我运行它时,SomeDerived 中的 this.x 是未定义的,因为它没有等待在 SomeBase 中设置 super.ngOnInit() 结果,并且它正在继续。我对异步代码不是很好,你能帮我理解为什么会这样吗?

【问题讨论】:

    标签: javascript angular asynchronous async-await


    【解决方案1】:

    我将创建一个实现 ngOnInit 方法的基础组件。在这个基础组件中,您正在创建另一个在异步方法执行后调用的方法(例如 onComponentCreated)。然后,您的派生类没有实现 OnInit,但它正在实现您的基类,因此正在执行 onComponentCreated。

    export class SomeDerived extends SomeBase {
          ................
          public onComponentCreated(): Promise<void> {
             ........
             this.getBy(this.x);
             ........
          } 
        }
    
     export class SomeBase implements OnInit {
         public x: any;
         ........
         public ngOnInit() {
           ........
           this.fetch().subscribe(result => {
              this.x = result;
              this.onComponentCreated();
           });
         }
    
        public abstract onComponentCreated();
    
    
        public async fetch(): Observable<void> {
            return new Observable(observer => {       
               const someId = await this.requestService.fetchId().toPromise().id;
               const result = await this.requestService.fetchX(someId).toPromise();
               observer.next(result)
           });
         }
        }
    

    【讨论】:

      【解决方案2】:
       public async fetch(): Promise<void> {
         return new Promise( async (resolve, reject) => {
            const someId = await this.requestService.fetchId().toPromise().id;
            this.x = await this.requestService.fetchX(someId).toPromise();
            resolve();
         });
       }
      

      你需要返回一个Promise否则你不能使用await

      【讨论】:

        猜你喜欢
        • 2020-06-24
        • 2014-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-09
        • 2019-07-07
        相关资源
        最近更新 更多