2017-07-13 11 views
2

内部に約束を持っている私のforEachループを待つことに問題があります。私は、スクリプトが終了するのを待つソリューションを見つけることができません。私はsomeFunctionを非同期にすることはできません。代わりにforEach()使用map()内部が約束してforEachを待つ

makeTree: function (arr) { 
arr.forEach(function (resource) { 
    someModule.someFunction(resource).then(function() { //a Promise 
     //do something with the resource that has been modified with someFunction 
    }) 
}); 
// do something after the loop finishes 

}

+0

anglejsを使用していますか? –

答えて

1

約束の配列を作成し、

makeTree: function (arr) { 
    var promises = []; 
    arr.forEach(function(resource) { 
     promises.push(someModule.someFunction(resource)); 
    }); 
    Promise.all(promises).then(function(responses) { 
     // responses will come as array of them 
     // do something after everything finishes 
    }).catch(function(reason) { 
     // catch all the errors 
     console.log(reason); 
    }); 
} 

あなたはこのlinkを参照することができ、これを試してみてくださいPromise.all()

let promiseArr = arr.map(function (resource) { 
    // return the promise to array 
    return someModule.someFunction(resource).then(function (res) { //a Promise 
     //do something with the resource that has been modified with someFunction 
     return transformedResults; 
    }) 
}); 

Promise.all(promiseArr).then(function(resultsArray){ 
    // do something after the loop finishes 
}).catch(function(err){ 
    // do something when any of the promises in array are rejected 
}) 
1

を使用するには、 Promise.allとsiの詳細例を挙げなさい。

関連する問題