2017-08-29 13 views
-2

これは初回ですので、基本的にforEachが完了しました。それ以降の処理のために別の関数を呼び出す場合は、1回だけforEachを使用して印刷します。insertIDBEvents次回の呼び出しでは印刷されません。 forEachに約束を使用する正しい方法は何ですか?promise inisde forEachの使い方forEachのチェックは完了しましたか?

nodeCtrl.js

var ctr = 0; 
    var insertIDBEvents = []; 
    data.forEach(function(element, index, array) { 
     event = JSON.parse(element.variables.event.value); 
     if (typeof element.variables.caseIdFound !== 'undefined') { 
      //asynchronous(function(data){ 
      Promise.all(array) 
       .then(function(element) { 
        ctr++; 
        console.log("caseIdFound boolean", element.variables.caseIdFound.value); 
        insertIDBEvents.push(element); 
        console.log(insertIDBEvents); 
        if (ctr === array.length) { 
         console.log('IDBinsert', JSON.stringify(insertIDBEvents)); 
        anotherFunction(insertIDBEvents) 
        } 
       }) 

     } 

    }); 

anotherIDBEvents (data) { 
    // do something with data 
} 

答えて

1

反復でPromise.allを使用する方法、それらの要素に対して必要な非同期動作を行う約束の配列に要素のあなたの配列をマッピングした後の配列を渡すことですPromise.allに約束します。だからここ

は、一般的な考え方です:Promise.allが外側にあるので

Promise.all(
    arrayOfElements.map(
    element => (
     functionThatReturnsAPromise(element) 
    ) 
) 
) 
.then(results => { 
    // ... 
}) 
+0

私が条件とその配列がまだのforEach – hussain

+1

@hussainによって処理されているが、そのように動作していない場合、あなたは同期と非同期コードをそのように混在させることはできませんだけで内部の約束を適用したかったです。 –

0

はあなたのコードを並べ替えます。また、配列の値はPromisesである必要があります。

上記のコードは明らかに機能しないので、少し難しいですが、データ配列をマップして各要素を約束してから、そのすべてを約束してPromise.allにダンプすることをお勧めします。

このような何か:

var ctr = 0; 
var insertIDBEvents = []; 

Promise.all(data.map(element => { 
    event = JSON.parse(element.variables.event.value); 

    if (typeof element.variables.caseIdFound !== 'undefined') { 
    ctr++; 
    console.log("caseIdFound boolean", element.variables.caseIdFound.value); 
    insertIDBEvents.push(element); 
    console.log(insertIDBEvents); 
    if (ctr === array.length) { 
     console.log('IDBinsert', JSON.stringify(insertIDBEvents)); 
     anotherFunction(insertIDBEvents) 
    } 
    } 
})).then(() => { 
    anotherIDBEvents(data); 
}); 
+0

いくつかのイベントは 'element.variables.caseIdFound'未定義の値を持っています。これらのイベントをanotherFunctionにプッシュしたくないので、anotherFunctionに値を持つプッシュイベントだけでした。残りのイベントはPromise.allでいくつかの他のロジックで処理されます – hussain

+0

@hussain '.filter()'のようなものを追加して、マップ関数を呼び出す前にデータを除外することができます。 – samanime

0

あなたはその後、Promise.all()に配列を渡し、条件によるフィルタリング、最初の約束のあなたの配列を構築したい、または他の一般的なアプローチは、要素の配列を構築し、Promise.map()を使用しています(使用しているライブラリがそれをサポートしている場合)、各要素に対して同じ約定をインスタンス化するのではなく、繰り返しごとに同じコードを実行する必要があります。

const anotherFunction = element => { 
    // do something with data 
    return element 
} 

const elements = data.map(element => { 
    return !!element.variables.caseIdFound 
}) 

Promise.map(elements, element => { 
    return anotherFunction(element) 
}).then(res => { 
    //handle resolution 
}).catch(err => { 
    //handle exceptions 
}) 
関連する問題