【问题标题】:JS - Async Await - second function doesn't wait for first function to complete, then first function executes againJS - 异步等待 - 第二个函数不等待第一个函数完成,然后第一个函数再次执行
【发布时间】:2020-10-30 07:43:52
【问题描述】:

我正在尝试使用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 函数嵌套到 loadUsers 的订阅范围内。在这之后我还有其他事情要做,而且它变得越来越嵌套。

【问题讨论】:

  • loadUsers() 不返回 Promise
  • 从上面显示的代码中,您的loadUsers 被多次调用的原因尚不清楚。 loadUsers 不会返回 Promise 和 loadOwner 调用 loadUsers,但不会对 result 做任何事情。一个更完整的示例将有助于诊断您面临的问题。
  • 不知道你为什么不简单地使用 observables。如果您仍然有可用的 rxjs,则通常不需要异步/等待和承诺。..

标签: javascript angular async-await


【解决方案1】:

你需要让你的 loadUsers() 成为一个 Promise。

在打字稿中:

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

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

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

并在调用时等待 loadUsers()。

【讨论】:

  • 一个Observable 有一个方法.toPromise()。应该改用那个
  • 等待Promise 用true 解析以仅取消该值,然后返回一个新的已解决的承诺? o.O
  • @Andreas 确实,有很多需要改变的哈哈,只是为了让 OP 了解那里发生的事情。
猜你喜欢
  • 2019-02-16
  • 2019-02-16
  • 1970-01-01
  • 2021-08-21
  • 2019-02-12
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
相关资源
最近更新 更多