Angularの非同期に問題があります。基本的に、私はいくつかのカードをループしています。特定の2種類のカードにはAPIコールが必要ですが、その種類のカードにはAPIコールは必要ありません。すべてのカードをループした後、完成したカードの配列が返されますが、私はAPI呼び出しを必要としないカードを返すだけです。 API呼び出しを必要とする代わりに、4つのすべてのなかった、しか返されるfinishedArrayは1枚のイエローカードが含まれています。この例ではAngular - forEachループでAPI呼び出しを待ってから配列を返す前に
// If color of colorCard is blue, it needs 2 API calls
// If color of colorCard is red, it needs 1 API call
// If color of colorCard is yellow, it doesn't need an API call
// Pretend for this example that colorCards has one yellow card, one blue card, and two red cards
var buildCards = function() {
var finishedArray = [];
var promises = [];
colorCards.forEach(function(e, i){
if (e.color === 'blue') {
promises.push(firstBlueApiCall);
var firstBlueIdx = 0;
promises.push(secondBlueApiCall);
var secondBlueIdx = 1;
} else if (e.color === 'red') {
promises.push(redApiCall);
var redIdx = 0;
}
// If card is blue or red, complete API calls before pushing to finishedArray
if (promises.length > 0) {
$q.all(promises).then(function(response) {
if (e.color === 'blue') {
e.firstBlueData = response[firstBlueIdx];
e.secondBlueData = response[secondBlueIdx];
} else if (e.color === 'red') {
e.redData = response[redIdx];
}
finishedArray.push(e);
promises = [];
});
// If card is yellow, push to finishedArray without making any API calls
} else {
finishedArray.push(e);
promises = [];
}
})
return finishedArray;
}
:
これは私がどのように働いているで作られた迅速なモックアップがありますカード。赤色/青色のカードがAPI呼び出しを完了するまで、どのように 'return finishedArray'を待機させることができますか?ここで
JavaScriptはシングルスレッドです。関数が完了すると、利用可能なデータまたは*未定*で実行される*保留中の*約束だけを返すことができます。 – georgeawg