簡體   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