在Angular 1.X应用程序中,如果我想处理两个承诺的结果,有没有比这更优雅的方法:
function doSomethingWithBothResults(result1, result2) {
return result 1 + result2;
}
$http.get('/endpoint1').then(function (result1) {
$http.get('/endpoint2').then(function (result2) {
doSomethingWithBothResults(result1 + result2);
});
});虽然这在只有2个承诺的情况下是可以的,但更多的承诺会导致更深的嵌套,这是令人不安的。
发布于 2017-07-28 22:09:28
您可以使用Promise.all来实现这一点。
对于您的代码片段,应该是这样的:
let promises = [];
promises.push($http.get('/endpoint1'));
promises.push($http.get('/endpoint2'));
Promise.all ( promises ).then ( function ( data ) {
//Data from all the promises
} ).catch ( function ( error ) {
//Error
} );在回调函数中,data是一个数组,它的每个元素都包含promise的已解析值。此外,data中元素的顺序与您在数组中推送它们的顺序相同。
这将是有用的,如果你的承诺是独立的彼此。如果他们需要之前承诺的结果,那么链接是可行的。此外,这将开始同时解析两个promises,而链接方法将等待一个promises解析,然后开始解析下一个promises
https://stackoverflow.com/questions/45375550
复制相似问题