我为我的 Angular 应用程序创建了一个自定义 loaderService,它在后端处理一个请求(或一组请求)时提供一个加载微调器。这是我的代码:
export class ComponentOne {
constructor(loaderService: LoaderService, orderService: OrderService) {}
...
...
method() {
this.loaderService.display(true);
this.orderService.firstRequest()
// the misspelled word causes a 500 error
.then((response) => this.orderService.methodWithWrongInput('misspelled_word'))
// but it still executes the following then
.then(() => this.method2())
.catch(() => null)
.then(() => this.loaderService.display(false));
}
...
}
我在请求之前显示微调器,但我想确保无论请求成功还是失败都关闭它。这就是为什么我将 catch
和最后的 then
放在底部的原因。代码工作正常,但是当我调试它时,我意识到即使第二个请求(带有故意拼错的单词)失败了,method2()
仍然被调用。或者它真的失败了吗?
我的问题是,在链接请求时 catch 方法如何工作。我以为如果请求失败,我们会直接进入 catch 方法,但我可能错了。
编辑: 原来我错了 method2()
被调用。见 T.J. Crowder 的更多回答。
最佳答案
...I realized that even though the second request (with the intentionally misspelled word) fails,
method2()
is still being called...
我怀疑您误解了您在调试器中看到的内容,在这种情况下很容易做到这一点。
在这段代码中:
method() {
this.loaderService.display(true);
this.orderService.firstRequest()
// the misspelled word causes a 500 error
.then((response) => this.orderService.methodWithWrongInput('misspelled_word'))
// but it still executes the following then
.then(() => this.method2())
.catch(() => null)
.then(() => this.loaderService.display(false));
}
这是发生了什么:
this.loaderService.display(true);
运行this.orderService.firstRequest()
运行并返回一个 promise.then((response) => this.orderService.methodWithWrongInput('misspelled_word'))
运行 - 不是回调中的部分,只是然后
。它在 promise 上注册一个解析处理程序并返回一个新的 promise。.then(() => this.method2())
运行——同样,只是then
调用,而不是它的回调。它返回另一个新的 promise 。.catch(() => null)
运行——同样,只是catch
调用,而不是它的回调。它返回另一个新的 promise 。.then(() => this.loaderService.display(false))
运行 - 同样,只是then
调用,而不是它的回调。它返回另一个新的 promise 。
然后 稍后,firstRequest()
的 promise 解决,并且
(response) => this.orderService.methodWithWrongInput('misspelled_word')
运行并返回一个新的 promise
然后稍后,该 promise 被拒绝,并且
() => null
(在您的catch
处理程序中)运行并返回null
,它解析关联的 promise (例如,转换什么是拒绝变成决议)() => this.loaderService.display(false)
运行,因为此时链已解析(未拒绝)(感谢上面的#8)
所以在调试器中,您会看到执行光标跨过 then
对 method2
的调用,在上面的初始序列 (#4) 中链是同步设置;但这只是将处理程序添加到链中。您不会看到 method2
实际上被调用,因为当解决/拒绝发生时该回调永远不会被触发(在 methodWithWrongInput
拒绝的情况下)
关于angular - 链接 HTTP promise 时如何调用 catch 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46543445/