首页 > 解决方案 > Promise Chaining:多个 then 调用

问题描述

以下代码段的输出是什么,为什么?

new Promise((resolve,reject) => resolve(10))
.then(data=>data*2)
.then(data=>{throw Error('error')})
.then(data=>10+10)
.catch(error=>10)
.then(data=>data*3)
.catch(error => console.error('IN ERROR',error))
.then(data=>console.log('IN DATA',data))

标签: javascriptpromise

解决方案


IN DATA 30

为什么?让我们一个一个去

1-new Promise((resolve,reject) => resolve(10))决心10

2-.then(data=>data*2)解析为20(10 * 2 = 20)

3-.then(data=>{throw Error('error')})决心error

4-.then(data=>10+10)被跳过(因为 prev 行抛出错误)

5-.catch(error=>10)决心10

6-.then(data=>data*3)解析为30(3 * 10 = 30)

7-.catch(error => console.error('IN ERROR',error))被跳过(因为 prev 行没有被捕获的错误)

8-.then(data=>console.log('IN DATA',data))打印IN DATA 30


推荐阅读