2017-05-31 5 views
0

これはAngularJSと私の要件である、すべての約束は次の反復の前に解決されるまで待ちます作品はループ

+0

あなたは* *あなたのインデントを修正していただけますか? – Bergi

+0

JavaScriptはシングルスレッドです。 'for'ループは**約束が解決される前に**完了します。ループを待たせることはできません。 – georgeawg

+0

あなたはそれが同期したかのように、あなたのロジックを記述関数にそれを入れて、[nsynjs](https://github.com/amaksr/nsynjs)同期キュータを経由してその機能を実行することができます。ここでは同様の例では機能「プロセス()」を参照してください:https://github.com/amaksr/nsynjs/blob/master/examples/browser-ajax-seq.js – amaksr

答えて

0

は約束の配列を作成し、すべての約束は解決されたときに実行するために$q.all(promise_array)を使用してループ圏の外に存在する最後の機能に移動し、行われ

// map array of `$q.all()` promises 
let promises = self.Scope.data.map((data) => { 
    //First asynchronous function 
    let promise_1 = self.EcritureService.createNewData(data).then(() => {}) 
    //Second asynchronous function 
    let promise_2 = self.OperationService.getOperation(data.idOperation).then((operation) => { 

    }) 
    //Third asynchronous function 
    let promise_3 = self.AccountService.getAccount(data.codeCompte).then((compte) => { 
    currentAccount = compte; 
    currentAccount.montant = currentAccount.montant + data.montant; 
    return currentAccount; 
    }).then((currentAccount) => { 
    //return promise of 4th inside `then()` of third 
    return self.AccountService.updateAccount(currentAccount).then(() => {}); 
    }); 

    // this `$q.all()` resolves when this mapped instance of above all resolve 
    return $q.all([promise_1, promise_2, promise_3]); 

}); 

// resolves when all the loop instances of `$q.all()` resolve 
$q.all(promises).then(()=>{ 
    // run completion code here 
}).catch(err=>{ 
    console.log('Something failed in promise chain') 
}) 
+0

ハ - それは豪華です:) $ Qの配列.allだから$ q.all'ed - それを愛する:)再帰的なループよりもはるかに良い! – IrishDubGuy

0

まず第一に、私は、あなたはおそらく、これらのサービスは、あなたがそれらの「promiseness」を回避しようとしていることを考えると約束、したくないと言うでしょう。だから、最も簡単な解決策は、約束の代わりに通常通りに戻るようにサービスを書き直すことです。

しかし、あなたの質問に答えます。第二部第一 - 第三に第四の約束をリンクする最も簡単な方法は、ちょうどこのように、第三.thenの内側にそれを置くことです:

//Third asynchronous function 
self.AccountService.getAccount(data.codeCompte).then((compte) => { 
      currentAccount = compte; 
      currentAccount.montant = currentAccount.montant+data.montant; 
      //Fourth one relies on the third result, So it must be executed sequentially 
      self.AccountService.updateAccount(currentAccount).then(() => { 
    }) 
}) 

あなたがハンドリングエラーを置くならば、中にあなたが置くことを決めるかもしれません代わりに.finally節で約束を入れ子にしました。ループが実際にそれを行うように設計されていないため、待つためにループを取得するためとして

。達成する最も簡単な方法は、独自のループを作成し、$ q.allを使用して約束をまとめることです。ループカウンタを追跡する必要があります。ループカウンタは$ q.allの.thenでインクリメントし、必要な回数のループが終了したときに壊れる再帰関数を使用します。