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:
- It serializes
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).
- The
.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()
.
- Both
fn1
and fn2
will be called regardless of an error in either.
Another related question/answer: Understanding javascript promises; stacks and chaining
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…