Promise 面试题
收集了 Promise 相关的高频面试题,涵盖执行顺序、状态机制、错误处理、链式调用等核心知识点。每道题都可以运行查看实际输出。
答题技巧
- 同步代码先执行,微任务(Promise.then)在宏任务(setTimeout)之前
- Promise 状态一旦确定(fulfilled / rejected)就不可变
- then 返回的是新的 Promise,不是原来的
- catch 本质上是
.then(null, onRejected)的语法糖
题 1:执行顺序
经典事件循环入门题。考查同步代码与微任务的执行顺序。
答案: start → promise1 → end → then1
同步代码(start、promise1、end)先执行,then 回调作为微任务在同步代码之后执行。
题 2:setTimeout vs Promise
考查宏任务与微任务的优先级。
答案: 1 → 3 → 6 → 4 → 5 → 2
同步代码先输出 1、3、6;微任务输出 4、5;宏任务最后输出 2。
题 3:resolve 的值
resolve 一个 Promise 时,最终值是什么?
答案: value: 42
当 resolve 的值是一个 Promise 时,会"解包"——等待内部 Promise 完成后取其值。
题 4:then 返回值与链式调用
then 回调返回普通值 vs 返回 Promise 的区别。
答案: first then: 1 → second then: 2 → third then: 20
返回普通值会自动包装为 Promise.resolve(value);返回 Promise 则等待它完成。
题 5:错误捕获
catch 如何捕获链中的错误,catch 之后还能继续 then 吗?
答案: then1: ok → catch: boom → then3: recovered
throw 会被最近的 catch 捕获;catch 返回的值会传递给后续的 then。
题 6:Promise.all 错误处理
Promise.all 中有一个失败会怎样?
答案: 失败: fail
Promise.all 只要有一个 Promise 失败,整体就失败,返回第一个失败的原因。
题 7:async/await 与微任务
await 后面的代码相当于在 then 中执行。
答案: before → asyncTask executor → after → await 得到: result → 继续处理: result!
题 8:Promise 状态不可变
resolve/reject 只会生效第一次调用。
答案: fulfilled: 第一次 + 状态一旦确定就不可更改
状态从 pending 变为 fulfilled 后,后续的 resolve/reject 调用都会被忽略。
题 9:嵌套 Promise 执行顺序
多层嵌套的 Promise 回调执行顺序。
答案: 1 → 2 → 8 → 3 → 4 → 7 → 5 → 6
注意第 7 步:外层第一个 then 返回的 Promise 在内层第一个 then 之后 resolve。
题 10:综合题
综合考查同步代码、微任务队列、多个 Promise 链的执行顺序。
答案: B → E → H → C → F → D → G → A