JS-异步等待-第二个函数不等待第一个函数完成,然后第一个函数再次执行

时间:2020-07-09 16:31:02

标签: javascript angular async-await

我尝试使用async await中的Angular 10首先通过http请求从后端数据库(带有MariaDB的Spring Boot)中加载用户列表,然后在加载列表之后,为一位特定用户过滤该列表。 但是不知何故,loadUsers()不断执行两次,如您在我文章结尾的结果日志中所见。

这就是我希望代码能正常工作的方式:

  1. 加载所有用户-> console.log我所有用户的列表(a)

  2. 过滤用户列表,然后console.log这个过滤过的用户->(b)

但不是a)-> b),而是a)-> b)-> a)。在哪里首先a)为空,因为http请求尚未完成,然后b)也为空,因为用户尚未加载,然后又是a),则在用户加载之后又为空?

ngOnInit() {
  this.loadOwner();
}

loadOwner = async () => {
  const result = await this.loadUsers()  // I'm not doing anything with the result, maybe that's the reason?
  // do something else here after users loading completes
  this.user= this.users.filter(user => user.id === this.product.userId)[0]  
  console.log("The user: " + this.user)  // b) (should get logged as last)
}

loadUsers() {
this._update.currentUsers$.subscribe(users => {
    this.users = users;
    console.log("my users: " + this.users)  // a) (should get logged first)
})
}

这是我得到的最后一个日志a)-> b)-> a)结构:

result

过滤和http请求正在工作,我已经有了预期的最终结果,但希望使用异步等待来获得更干净的代码,而不是将loadUser函数嵌套到loadUsers的订阅范围中。此后,我还有其他事情要做,并且它越来越嵌套。

1 个答案:

答案 0 :(得分:-2)

您需要使loadUsers()成为一个承诺。

在打字稿中:

loadUsers(): Promise<any> {
  // some code
  return Promise.resolve(true);
}

实际上,在您的情况下,您将遇到另一个问题,因为您实际上应该在loadUsers()中的subscribe上等待。因此,您可以这样做:

async loadUsers(): Promise<any> {
  return this._update.currentUsers$.toPromise();
}

并在调用loadUsers()时等待它。