javascript - 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))
解决方案
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
推荐阅读
- azure - 天蓝色 dns 重定向到 www
- php - 使用 header('HTTP/1.1 在 PHP 中设置 HTTP 响应状态码
')? - c# - Unity Inspector 未报告与脚本相同的轮换
- ios - 快速过滤领域列表
- java - /proc/stat、/proc/uptime 和 /proc/[pid]/stat 中的时间是以滴答声还是秒数表示的时间是准确的还是近似的
- javascript - nodejs中的导入错误:SyntaxError:JSON中位置0处的意外标记u
- php - 检查刀片中是否使用了变量(laravel)
- python - 在 NaN 中将 predict_proba 与 X_test 结果合并
- mysql - 在我的数据库中保存用户数据库连接
- python - 为什么我的代码将文件与服务器文件一起保存,而不是在上传文件夹中?