Promise 原理详解
一句话结论:Promise 的
then/catch/finally回调走“微任务队列”;同一轮宏任务结束后会被立刻清空,因此通常早于setTimeout。
1. Promise 的三个状态
pending:初始态fulfilled:成功(不可再变)rejected:失败(不可再变)
2. 两个容易踩坑的点
new Promise(executor)里的executor是同步执行的then的回调不是同步执行,而是排入微任务
console.log(1);
new Promise((resolve) => {
console.log(2);
resolve();
}).then(() => console.log(4));
console.log(3);
// 常见:1 2 3 4
3. 链式调用为什么能“串起来”
then返回一个新 Promise- 回调返回值会决定新 Promise 的状态(值/Promise/抛错)