Wil*_*dow 4 javascript promise angularjs q
我有一系列的承诺和每个承诺电话http.get().
var items = ["URL1", "URL2", "URL3"];
var promises = [];
//on each URL in items array, I want to create a promise and call http.get
items.forEach(function(el){
return promises.push($http.get(el));
});
var all = $q.all(promises);
all.then(function success(data){
console.log(data);
}).catch(function(reason){
console.log("reason is", reason);
});
Run Code Online (Sandbox Code Playgroud)
在我的情况下发生了什么
URL2.get没有得到解决,它立即触发catch()了$q.all.由于这种失败,all.then()永远不会被调用.
我想要的是
即使其中一项承诺遭到拒绝,我也希望所有的承诺能够继续下去.
我发现了一个类似的帖子,但解决方案建议使用另一个名为Kris Kowal的Q的角度蛋糕.所以我想知道如何在不使用外部包的情况下实现它?
一个简单的hack可能是向promises添加一个catch块,返回null,并从promise.all结果中过滤null结果,如:
let items = ["URL1", "URL2", "URL3"]
, promises = items.map(url => $http.get(url).catch(e => null))
, all = $q.all(promises).then(data => data.filter(d => !!d))
all.then(data => {
// do something with data
}).catch(e => {
// some error action
})
Run Code Online (Sandbox Code Playgroud)
ES5中同样的事情:
var items = ["URL1", "URL2", "URL3"]
, promises = items.map(function(url){
return $http.get(url).catch(function(e){return null})
})
, all = $q.all(promises).then(function(data){
return data.filter(function(d){return !!d}) // filter out empty, null results
})
all.then(function(data){
// do something with data
}).catch(function(e){
// some error action
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4765 次 |
| 最近记录: |