本文介绍了promise.then.then 和 promise.then 之间有区别吗?答应.然后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下两个有区别吗?

I want to know is there a difference between following two?

  1. aPromiseObj.then(fn1).then(fn2).catch(fn3);
  2. 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".

假设 f1f2 表示返回承诺的异步操作,是的,存在显着差异.对于选项 1:

Assuming that f1 and f2 represent asynchronous operations that return promises, yes there is a significant difference. For option 1:

  1. 它序列化 fn1fn2 以便 fn2fn1 返回的 promise 之前不会被调用已解决.
  2. .catch() 适用于 fn1fn2 中的错误,或者 aPromiseObj 拒绝.
  3. 如果 fn1 拒绝,则不会调用
  4. fn2.
  1. It serializes fn1 and fn2 so that fn2 is not called until after the promise returned by fn1 has been resolved.
  2. .catch() applies to an error in either fn1 or fn2 or if aPromiseObj rejects.
  3. fn2 will not be called if fn1 rejects.

对于选项 2:

  1. fn2 不会等待 fn1 解析.fn2fn1 返回后立即调用,类似于 fn1();fn2();.这意味着由 fn1fn2 启动的异步操作将同时进行(有时称为并行运行而不是串行运行).
  2. .catch() 不适用于任何一个,因为它不在由 .then() 调用创建的承诺中.选项 2 中的 .catch(),仅适用于 aPromiseObj 拒绝,而不适用于 f1()f2().
  3. fn1fn2 都会被调用,而不管两者中的任何一个是否有错误.
  1. 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).
  2. 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().
  3. Both fn1 and fn2 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 之间有区别吗?答应.然后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:26