'What is the difference between doing `<..>.get().then().then().catch().finally()` vs `<...>.get().then().catch().then().finally` [duplicate]
I am learning a bit about promises in Javascript and am wondering if there is any difference when reordering in the following way <...>.get().then().then().catch().finally() vs <...>.get().then().catch().then().finally()?
Solution 1:[1]
Yes, they are different.
Let's say you have this:
<...>.get().then(() => A()).then(() => B()).catch(() => ErrorHandling()).finally(() => D())
<...>.then(() => A()).catch(() => ErrorHandling()).then(() => B()).finally(() => D())
You could translate this to an await/async representation:
// <...>.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();
}
In the first case, B won't be executed if either get or A results in an error. In the second case B will be executed even if get or A results in an error, the only case where it won't be executed is if ErrorHandling results in an error.
So the first one is used if B depends on get and A to be successfully executed. The second case is used e.g. if B should do some thing not matter if get or A was succesfull.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
