我正在尝试使用异步/等待模式来处理如果以其他方式实现可能被视为"回调地狱"的场景。
这是一个非常愚蠢的代码版本。真正的代码有大约 5 个条件 HttpClient 调用,基于第一次调用的数据(不是我的 api...(,这就是我首先使用 async/await 模式的原因。
async blah(): Promise<boolean> {
try {
let resp = await this.http.get("https://httpstat.us/500").toPromise();
console.warn("you should not see this");
// the real code will logically call the api multiple times based on conditonal data from resp
// hence the attempted usage of async/await to avoid "callback hell"
// blah() will eventually return an object.
return true;
}
catch (err) {
console.error("caught inside blah()");
throw err;
}
}
ionViewDidLoad() {
this.blah().then(data => {
console.warn('okokokok');
}).catch(error => {
console.error(error)
});
}
会发生什么,我可以看到调用实际上是 500,但代码继续,以下内容打印到控制台:
polyfills.js:3 GET https://httpstat.us/500/ 500 (Internal Server Error)
main.js:927 you should not see this
main.js:940 okokokok
如您所见,它没有捕获 500(或我测试过的任何其他 http 状态(
我正在测试的设备是运行 P 的 Pixel 2,控制台数据来自 Chrome 设备检查器会话。
任何建议将不胜感激。
**编辑:这显然是离子和角度组合的问题...它应该工作...
**编辑:事实证明100%是一个角度问题...不是框架本身,而是拦截器的实现方式。 我将把它留在这里,而不是在极少数情况下删除这个问题,其他人需要它。
如果我回答了你的问题,你想做级联调用,所以你发出 http 请求,并根据响应你想做另一个 http 调用。如果是这种情况,那么您应该考虑使用switchMap
运算符:
this.http.get("https://httpstat.us/500").pipe(
switchMap( result => {
if(result.a === 5) {
return this.http.get("some server api url");
}
return return this.http.get("another server api url");
})
)
然后你以rxjs
的方式处理错误。
查看级联调用