I want to know is there a difference between following two?
aPromiseObj.then(fn1).then(fn2).catch(fn3);
aPromiseObj.then(fn1); aPromiseObj.then(fn2); aPromiseObj.catch(fn3);
Will the work flow changed?
ps: I am in angular environment, though I would like to think this in a broader term.
then() The then() method returns a Promise . It takes up to two arguments: callback functions for the success and failure cases of the Promise .
A promise is a pattern for handling asynchronous operations. The promise allows you to call a method called "then" that lets you specify the function(s) to use as the callbacks.
In summary: then : when a promise is successful, you can then use the resolved data. catch : when a promise fails, you catch the error, and do something with the error information. finally : when a promise settles (fails or passes), you can finally do something.
Here, Promise. all() method is the order of the maintained promises. The first promise in the array will get resolved to the first element of the output array, the second promise will be a second element in the output array and so on.
You have asked about "chaining" vs. "branching".
Assuming that f1
and f2
represent asynchronous operations that return promises, yes there is a significant difference. For option 1:
fn1
and fn2
so that fn2
is not called until after the promise returned by fn1
has been resolved..catch()
applies to an error in either fn1
or fn2
or if aPromiseObj
rejects.fn2
will not be called if fn1
rejects.For option 2:
fn2
does not wait for fn1
to resolve. fn2
is called as soon as fn1
returns similar to fn1(); fn2();
. This means the async operations started by fn1
and fn2
will both be in-flight at the same time (sometimes referred to running in parallel instead of running serially)..catch()
does not apply to either because it is not on the promise that is created by either of the .then()
calls. The .catch()
in option 2, only applies to if aPromiseObj
rejects, not f1()
or f2()
.fn1
and fn2
will be called regardless of an error in either.Another related question/answer: Understanding javascript promises; stacks and chaining
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With