【发布时间】:2020-10-30 07:43:52
【问题描述】:
我正在尝试使用Angular 10中的async await首先通过http请求从我的后端数据库(带有MariaDB的Spring Boot)加载用户列表,然后在加载列表后过滤该列表对于一个特定的用户。
但不知何故,loadUsers() 不断被执行两次,正如您在我帖子末尾的结果日志中看到的那样。
以下是我希望我的代码工作的方式:
-
加载所有用户 -> console.log 我所有用户的列表 (a)
-
过滤用户列表,然后 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