繁体   English   中英

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

[英]JS - Async Await - second function doesn't wait for first function to complete, then first function executes again

我正在尝试在Angular 10中使用async await来首先使用 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) 结构得到的最终日志:

结果

过滤和 http 请求正在工作,我已经有了预期的最终结果,但希望使用异步等待获得更清晰的代码,而不是将 loadUser function 嵌套到订阅 Z31A1FD140BE4BEF2D11E121ECZZA18 中。 在这之后我还有其他事情要做,而且它变得越来越嵌套。

您需要将您的 loadUsers() 设为 Promise。

在 Typescript 中:

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

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

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

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

暂无
暂无

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

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