Angular 5 等待不等待 [英] Angular 5 Await Not Waiting

查看:38
本文介绍了Angular 5 等待不等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行下面的代码时,checkCard 函数在 getTimecard 函数完成之前运行.

When I run the code below, the checkCard function runs before the getTimecard function is finished.

getTimecard() {
  this._service.getTimecard().subscribe(
  data => {
    this.sending = true;
    this.timecards = data;
  },
  err => {
    this.sending = false;
    console.error(err);
  },
  () => {
    this.sending = false;
  }
);
}

checkCards() {
  console.log('timecards', this.timecards);
  //code dependent on timecard data
}

async onSubmit() {
  await this.getTimecard();
  this.checkCards(); 
}

为什么 checkOverlap 不等待 getTimecard 返回其数据?

Why Isn't checkOverlap waiting for getTimecard to return its data?

推荐答案

为了使函数可等待,函数需要返回一个 Promise.

To make a function awaitable the function needs to return a Promise.

loadTimecards() {
   return new Promise(resolve => {
     this.sending = true;
     this._service.getTimecard().subscribe(data => {
       this.sending = false;
       this.timecards = data;
       resolve();
     });
  });
}

这篇关于Angular 5 等待不等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆