2017-07-13 133 views
2

我有一個問題,等待我的forEach循環,裏面有一個承諾,完成。我找不到可以讓腳本等待它完成的解決方案。我不能使someFunction異步。等待每個承諾內完成

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

你使用的是angularjs嗎? –

回答

1

代替forEach()使用map()創建承諾的數組,然後使用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

試試這個,

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與si多個例子。