本文介绍了promise.then.then 和 promise.then 之间有区别吗?答应.然后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道以下两个有区别吗?
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);
工作流程会改变吗?
ps:我处于有角的环境中,但我想从更广泛的角度来考虑这一点.
ps: I am in angular environment, though I would like to think this in a broader term.
推荐答案
您已经询问了 链接" 与 分支".
You have asked about "chaining" vs. "branching".
假设 f1
和 f2
表示返回承诺的异步操作,是的,存在显着差异.对于选项 1:
Assuming that f1
and f2
represent asynchronous operations that return promises, yes there is a significant difference. For option 1:
- 它序列化
fn1
和fn2
以便fn2
在fn1
返回的 promise 之前不会被调用已解决. .catch()
适用于fn1
或fn2
中的错误,或者aPromiseObj
拒绝. 如果 fn2
.
fn1
拒绝,则不会调用 - It serializes
fn1
andfn2
so thatfn2
is not called until after the promise returned byfn1
has been resolved. .catch()
applies to an error in eitherfn1
orfn2
or ifaPromiseObj
rejects.fn2
will not be called iffn1
rejects.
对于选项 2:
fn2
不会等待fn1
解析.fn2
在fn1
返回后立即调用,类似于fn1();fn2();
.这意味着由fn1
和fn2
启动的异步操作将同时进行(有时称为并行运行而不是串行运行)..catch()
不适用于任何一个,因为它不在由.then()
调用创建的承诺中.选项 2 中的.catch()
,仅适用于aPromiseObj
拒绝,而不适用于f1()
或f2()代码>.
fn1
和fn2
都会被调用,而不管两者中的任何一个是否有错误.
fn2
does not wait forfn1
to resolve.fn2
is called as soon asfn1
returns similar tofn1(); fn2();
. This means the async operations started byfn1
andfn2
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 ifaPromiseObj
rejects, notf1()
orf2()
. - Both
fn1
andfn2
will be called regardless of an error in either.
另一个相关问题/答案:理解javascript承诺;堆栈和链接
Another related question/answer: Understanding javascript promises; stacks and chaining
这篇关于promise.then.then 和 promise.then 之间有区别吗?答应.然后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!