Promise 链
解释 then 链如何传值、吞错与返回 Promise 的扁平化,避免回调金字塔回潮。
#type / concept
#status / growing
#tech / dev
#resource / javascript
[!info] 关联笔记
- 前置:Promise · async/await
- 相关:事件循环
Promise 链
这个概念为什么出现
多个异步步骤若嵌套回调会难读;若错误 then 链却不 return,会出现“断链”与未处理 rejection。
[!abstract] 一句话理解 每个
then返回新 Promise;返回值成为下一环入参,抛错或返回 rejected Promise 进入失败链。
最小示例
Promise.resolve(1)
.then((n) => n + 1)
.then((n) => {
if (n < 0) throw new Error('neg')
return n * 10
})
.then((n) => console.log('ok', n))
.catch((e) => console.log('err', e.message))
期望:ok 20。
关键规则
then里 return 普通值 → 下一环 fulfilled- return Promise → 扁平衔接
- throw → 走 catch
- catch 后还可继续 then(恢复)
常见误区
[!warning] 常见误区:then 中开了 Promise 却不 return 外层不会等它,错误也可能丢失。
本节总结
链式 then 的本质是组合新 Promise;return 是契约。
自测题
- catch 之后是否还能 then?
参考答案
能;catch 正常返回后后续 then 收到恢复后的值。