# 基础版本
- 设定三个状态
PENDING、FULFILLED、REJECTED,只能由PENDING改变为FULFILLED、REJECTED,并且只能改变一次 MyPromise接收一个函数executor,executor有两个参数resolve方法和reject方法resolve将PENDING改变为FULFILLEDreject将PENDING改变为FULFILLEDpromise变为FULFILLED状态后具有一个唯一的valuepromise变为REJECTED状态后具有一个唯一的reason
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
function MyPromise(executor) {
this.state = PENDING;
this.value = null;
this.reason = null;
const resolve = (value) => {
if (this.state === PENDING) {
this.state = FULFILLED;
this.value = value;
}
}
const reject = (reason) => {
if (this.state === PENDING) {
this.state = REJECTED;
this.reason = reason;
}
}
try {
executor(resolve, reject);
} catch (reason) {
reject(reason);
}
}
@前端进阶之旅: 代码已经复制到剪贴板
# then方法
then方法接受两个参数onFulfilled、onRejected,它们分别在状态由PENDING改变为FULFILLED、REJECTED后调用- 一个
promise可绑定多个then方法 then方法可以同步调用也可以异步调用- 同步调用:状态已经改变,直接调用
onFulfilled方法 - 异步调用:状态还是
PENDING,将onFulfilled、onRejected分别加入两个函数数组onFulfilledCallbacks、onRejectedCallbacks,当异步调用resolve和reject时,将两个数组中绑定的事件循环执行。
function MyPromise(executor) {
this.state = PENDING;
this.value = null;
this.<