【发布时间】:2017-06-12 15:11:13
【问题描述】:
我有一个获取数据的服务,我用不同的参数调用了 5 次以获取不同的数据。 我调用了一个函数在成功的情况下执行:它工作正常。 但是如果 5 个调用中的一个失败,我需要做一些其他没有发生的事情:它总是进入成功功能。 我正在使用离子 4 角度 2 这是我的服务:
public getdataLookUps(type, lcid): Promise<string[]> {
return new Promise((resolve, reject) => {
if (this.data[type + lcid]) {
resolve(this.data[type + lcid]);
return;
}
this.authService.getToken().then(
(accessToken) => {
let headers = new Headers({'Authorization': 'bearer ' + accessToken});
let url = 'error url to test failure case';
this.http.get(url, {headers: headers})
.map(res => res.json())
.toPromise()
.then(
(res) => {
this.data[type + lcid] = res;
resolve(res);
},
(error) => {
reject(error);
}
);
}
);
});
}
然后我像这样包装调用服务的函数:(使用不同的参数重复 5 次):
public getAreas() {
return this.lookupsService.getdataLookUps('Region', this.lcid).then(
(res) => {
this.areas = res;
},
() => {
//todo
return Promise.reject('rejection error');
}
);
}
然后我调用 5 个函数:
ngOnInit() {
this.getCaseCategories();
this.getAreas();
this.getWeather();
this.getMifonProjects();
this.getUserInfo();
}
我在这里做 promise.all() :
ngAfterViewInit(){
Promise.all(
[
this.getCaseCategories(),
this.getAreas(),
this.getWeather(),
this.getMifonProjects(),
this.getUserInfo(),
]
).then(
() => {
this.loadMap();
},
() => {
this.showErrorMessage = true;
}
);
}
【问题讨论】:
-
如果我在 getArea() 包装函数中添加 return Promise.reject ,我得到这个错误:Uncaught (in promise): 1
-
避免
Promiseconstructor antipattern 中的getdataLookUps! -
@Bergi 我没听懂你
-
好吧,如果浏览器没有缓存任何内容,那么设置正确的
Cache-Control响应标头(并且-如果您打开了开发人员工具-取消选中覆盖网络选项卡中的“始终从服务器重新加载”复选框常规缓存处理)。
标签: javascript angular ionic-framework promise ionic2