簡體   English   中英

Angular 4 等待 promise/observable 進入循環

[英]Angular 4 wait for promise/observable into a loop

我找不到以下案例的有效解決方案

我想創建以下循環:

  1. ForEach 元素 (A) 數組
  2. 填充一個新數組 (B)
  3. 如果數組 (B) 中不存在鍵,則調用 Firebase 服務獲取數據
  4. 驗證數據並更新統計信息
  5. 在所有 (A) 鍵的末尾,生成執行統計信息並公開...

在繼續循環之前,我需要等待並鏈接 Firebase 數據的響應,問題是我需要在主循環中與來自 firebase 的數據進行交互(因此我無法在 subscribe 或 then 中實現它)

這是我要創建的代碼部分:

        // Here i check if user exist in array (B)
        let IDUtente = RifEvento.esisteUtente(Ordini.IDUtente) ;

        // If not exists i'll get data from FIREBASE
        if (IDUtente == -1) {
           let NewUser = new TipoStatUtente() ;
           NewUser.Chiave = Ordini.IDUtente ;
           IDUtente = RifEvento.Utenti.push(NewUser) ;
           IDUtente = IDUtente - 1 ;

           // I NEED to wait the end of this function before continue with loop
           this.statoUtente.getUser(IDUtente).then(dati => {
              console.log('Sottoscritto dati utente') ;
              let user : TipoSingoloUtente = dati ;
              NewUser.sonoscuola = user.sonoscuola ;
              if (!NewUser.sonoscuola) NewUser.Intestazione = user.Cognome + ' ' + user.Nome ; else NewUser.Intestazione = user.Scuola.Nome ;
              if (NewUser.sonoscuola) RifEvento.NumScuole += 1 ; else RifEvento.NumUtenti += 1 ;
           })

        }

        console.log(IDUtente) ;

        // Utente Esiste aggiorno le sue statistiche
        RifEvento.Utenti[IDUtente].Commissioni  += Ordini.costoCommissione ;
        RifEvento.Utenti[IDUtente].Incasso      += Ordini.parziale ;
        if (Ordini.Tipo == 'T') {                  
           RifEvento.Utenti[IDUtente].NumTicket += Ordini.numbiglietti ;
         } else {
           RifEvento.Utenti[IDUtente].NumIscritti  += 1 ;
           RifEvento.Utenti[IDUtente].NumBallerini += Ordini.IDBallerini.length ;
          }



      }

這是功能:

getUser(IDUtente) : Promise<TipoSingoloUtente> {
return this.db.object('user/' + IDUtente).map(users => {
return users ;})
.first()
.toPromise(); }

也許這個偽代碼可以顯示將異步調用放入循環中的實現,並確保所有調用都完成然后做一些事情

global count = 0
loop A[i] i:0->A.size
    var B
    if(A[i] NOT IN B)
        async_function(A[i], callback(result))
    else
        //do something
        count++ 
    end if  
end loop A

callback(result)
    //do something
    count++
    if count == A.size 
        //all data has been processed
        //you also can only count the asyn calls
        //final report
    else
        //do nothing
end callback

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM