[英]JS - Async Await - second function doesn't wait for first function to complete, then first function executes again
I'm trying to use async await
in Angular 10
to first load a list of users from my backend database (Spring Boot with MariaDB) with an http request and then, after the list is loaded, to filter that list for one specific user.我正在尝试在
Angular 10
中使用async await
来首先使用 http 请求从我的后端数据库(使用 MariaDB 的 Spring Boot)加载用户列表,然后在加载列表后为一个特定用户过滤该列表。 But somehow the loadUsers()
keeps getting executed twice, as you can see in the resulting log at the end of my post.但不知何故,
loadUsers()
一直被执行两次,正如您在我帖子末尾的结果日志中看到的那样。
Here's how I'd expect my code to work:这是我希望我的代码工作的方式:
load all users -> console.log the list of all my users (a)加载所有用户 -> console.log 我所有用户的列表 (a)
filter the users list and then console.log this one filtered user -> (b)过滤用户列表,然后 console.log 这个过滤的用户 -> (b)
But instead of a) -> b), I get a) -> b) -> a).但不是 a) -> b),而是 a) -> b) -> a)。 Where first a) is empty, because the http request wasn't finished yet, then b) which is therefore also empty, since the users are not loaded yet, and then again a), after the users were loaded?
第一个 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)
})
}
This is the final log that I'm getting with a) -> b) -> a) structure:这是我使用 a) -> b) -> a) 结构得到的最终日志:
The filtering and the http request are working, I had the expected end result already but wanted to have cleaner code with async await, instead of nesting the loadUser function into the subscribe scope of the loadUsers.过滤和 http 请求正在工作,我已经有了预期的最终结果,但希望使用异步等待获得更清晰的代码,而不是将 loadUser function 嵌套到订阅 Z31A1FD140BE4BEF2D11E121ECZZA18 中。 There are other things that I have to do after this and it gets more and more nested.
在这之后我还有其他事情要做,而且它变得越来越嵌套。
You need to make your loadUsers() a Promise.您需要将您的 loadUsers() 设为 Promise。
In Typescript:在 Typescript 中:
loadUsers(): Promise<any> {
// some code
return Promise.resolve(true);
}
Actually, in your case you will have another problem since you should actually await on the subscribe
in your loadUsers().实际上,在您的情况下,您将遇到另一个问题,因为您实际上应该在 loadUsers() 中等待
subscribe
。 You can therefore do it like so:因此,您可以这样做:
async loadUsers(): Promise<any> {
return this._update.currentUsers$.toPromise();
}
And await the loadUsers() when calling it.并在调用它时等待 loadUsers()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.