我有一个获取数据的服务,我用不同的参数调用了它 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();
}
我在这里承诺.all((:
ngAfterViewInit(){
Promise.all(
[
this.getCaseCategories(),
this.getAreas(),
this.getWeather(),
this.getMifonProjects(),
this.getUserInfo(),
]
).then(
() => {
this.loadMap();
},
() => {
this.showErrorMessage = true;
}
);
}
此代码有两个回调then
、一个成功处理程序和一个错误处理程序。如果代码与您所示的一样,则错误处理程序将返回成功结果,因此您的Promise.all()
将始终成功:
public getAreas() {
return this.lookupsService.getdataLookUps('Region', this.lcid).then(
(res) => {
this.areas = res;
},
() => {
//todo
}
);
}
不要添加错误处理程序,除非您确实能够处理此处的错误。相反,只需让错误传播到下一个处理程序:
public getAreas() {
return this.lookupsService.getdataLookUps('Region', this.lcid)
.then(res => this.areas = res);
}
现在,当数据查找失败时,您的Promise.all
会给您一个错误。
也停止嵌套你的承诺处理程序:
public getdataLookUps(type, lcid): Promise<string[]> {
if (this.data[type + lcid]) return Promise.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';
return this.http.get(url, {headers: headers})
.map(res => res.json())
.toPromise();
})
.then((res) => this.data[type + lcid] = res);
}
一旦你有一个Promise
只需返回Promise
就没有必要创建新的承诺。如果你的承诺成功处理程序创建了另一个承诺返回,以避免嵌套。你的错误处理程序除了传播错误之外什么也没做,所以当你没有嵌套承诺时,你也不需要它,只是让错误自然传播。
我通过删除 ngOnInit(( 中函数的调用来解决它;并保持所有内容与我上面的示例相同(不要更改getDataLookUps服务中的任何内容(