我正在学习一些关于承诺在Javascript中的知识,并且我想知道在以<...>.get().then().then().catch().finally() vs <...>.get().then().catch().then().finally()的方式重新排序时是否有什么不同
发布于 2022-02-27 12:02:23
用下面的链
<...>.get().then().then().catch().finally()catch方法将处理对链中所有先前承诺的拒绝,而使用以下链
<...>.get().then().catch().then().finally()catch方法不会处理上一个then方法返回的承诺的拒绝。
当您想要处理承诺拒绝并将其转化为实现catch方法返回的承诺以允许承诺链继续时,这种链非常有用。
如果第二链的结果承诺在某个地方使用,或者如果您要从如下所示的函数返回该链末尾的承诺,
function foo() {
return <...>.get().then().then().catch().finally();
}那么不使用另一个catch方法就可以了,因为在这种情况下,调用此函数的代码可以处理未被承诺链本身捕获和处理的承诺拒绝。
但是,如果不是这样的话,那么在上一次catch方法调用之后,您肯定还有第二个then方法。
发布于 2022-02-27 12:13:52
是的,它们是不同的。
假设你有这个:
<...>.get().then(() => A()).then(() => B()).catch(() => ErrorHandling()).finally(() => D())
<...>.then(() => A()).catch(() => ErrorHandling()).then(() => B()).finally(() => D())您可以将其转换为await/async表示:
// <...>.get().then(() => A()).then(() => B()).catch(() => ErrorHandling()).finally(() => D())
try {
await get();
await A();
await B();
} catch( ) {
await ErrorHandling()
} finally {
await D();
}
// <...>.then(() => A()).catch(() => ErrorHandling()).then(() => B()).finally(() => D())
try {
try {
await get();
await A();
} catch( ) {
await ErrorHandling()
}
await B();
} finally {
await D();
}在第一种情况下,如果B或A导致错误,则不会执行。在第二种情况下,B将被执行,即使get或A导致错误,唯一不会执行的情况是ErrorHandling导致错误。
因此,如果B依赖于要成功执行的get和A,则使用第一个方法。第二种情况是使用的,例如,如果B应该做一些事情,不管get还是A是否成功。
https://stackoverflow.com/questions/71284545
复制相似问题