在Promise中,使用catch和它的第二个参数有什么区别?
In a Promise, what's the difference between using catch and the 2nd argument of then?
这两个语句到底有什么区别?
funcThatReturnsAPromise()
.then(() => { /* success */ })
.catch(() => { /* fail */ });
funcThatReturnsAPromise()
.then(() => { /* success */ }, () => { /* fail */ });
除了.catch(fn)
是.then(null, fn)
的快捷方式外,您的示例中的区别在于
funcThatReturnsAPromise()
.then(() => { /* success */ })
.catch(() => { /* fail */ });
// is equivalent to
const p1 = funcThatReturnsAPromise()
const p2 = p1.then(() => { /* success */ })
const p3 = p2.catch(() => { /*
executed if p1 is rejected
executed if p2 is rejected
*/ })
而第二个是
funcThatReturnsAPromise()
.then(() => { /* success */ }, () => { /* fail */ });
// equivalent to
const p1 = funcThatReturnsAPromise()
const p2 = p1.then(
() => { /* success */ },
() => { /*
executed if p1 is rejected
(p2 will be actually resolved by the result of this function only when p1 is rejected)
*/ }
);
.catch(foo)
= .then(undefined, foo)
但是你的代码样本之间有一个区别:
funcThatReturnsAPromise()
.then(() => { /* success case of funcThatReturnsAPromise */ })
.catch(() => { /* both fail case of funcThatReturnsAPromise
and fail case of "then" function */ });
funcThatReturnsAPromise()
.then(() => { /* success case of funcThatReturnsAPromise */ },
() => { /* fail case of funcThatReturnsAPromise */ });
then(…)接受一个或两个参数,第一个参数用于实现回调,第二个是拒绝回调。如果有一个是省略或作为非函数值(默认值)传递Callback分别被替换。默认的执行回调简单地传递消息,而默认的拒绝回调只是重新抛出(传播)它接收到的错误原因。抓住(. .)只接受拒绝回调作为参数,并且自动替代默认的实现回调,正如刚才讨论的那样。换句话说,它相当于then(null,..):
p . then ( fulfilled );
p . then ( fulfilled , rejected );
p . catch ( rejected ); // or `p.then( null, rejected )`
then(..)和catch(..)也创建并返回一个新的promise,它可以表示承诺链的流量控制。如果履行或拒绝回调会抛出异常,返回的承诺是拒绝。如果任何一个回调返回一个即时的非承诺,non-then值,该值被设置为返回的承诺。如果执行处理程序特别返回Promise或then值,则该值被打开并成为返回的承诺的解析。
-选自《你不知道JS》,Kyle Simpson
相关文章:
- 当第二个参数为空时管理JavaScript调用的构造
- 筛选器's的第二个参数不起作用
- jQuery Datepicker BeforeShowDay 第二个参数
- 添加第二个参数时,Javascript函数将停止工作
- JavaScript 部分应用函数 - 如何仅绑定第二个参数
- 当第一个函数完成没有回调参数时执行第二个函数
- 何时适合将集合传递给主干模型构造函数第二个参数
- 为什么第二个函数参数在注释块中?只是好奇
- 下划线.js : _.where() 使用第一个参数,但不适用于第二个参数
- 如何在setInterval函数中生成第二个参数(持续时间)的随机持续时间值
- 如何将jquery对象转移到“On”方法(第二个参数)
- 是否可以将值数组作为第二个参数传递给 _.without() 函数
- JSON.stringify()工作不正常-第二个参数消失
- 结合Supercrollorama,TweenMax.to中第二个参数的含义是什么
- 简单`replace()`的第二个参数存在问题
- retrieve()中的第二个参数;始终在运行
- Javascript中reduce回调中的第二个参数
- 可以't在addEventListener方法的第二个参数中添加括号
- 骨干路由器多参数;第二个参数未定义
- JavaScript中JSON.stringify中的第二个参数