Promise有三种状态(pendding / fulfilled / rejected),状态改变不可逆,构造函数接受两个函数,resolve和reject。
resolve将promise的状态改为fulfilled,reject函数将promise的状态改为rejected,
分析
1.接受一个函数,函数接受两个函数作为参数:resolve 和reject;
2.一个存储promise状态的变量promiseState;
3.一个存储promise结果的变量promiseResult;
4.promiseState只能由 “pending”转为“fulfilled”,或者是‘pending’转为“rejected”
5.resolve改变为‘fulfilled’,reject改为‘rejected’,并且不许允许再次改变
function Promise(fun) { this.promiseState = "pending"; this.promiseResult = null; const resolve = (val) => { // 状态一旦改变,不允许再次执行了 if (this.promiseState !== "pending") return; this.promiseState = "fulfilled"; this.promiseResult = val; }; const reject = (err) => { // 状态一旦改变,不允许再次执行了 if (this.promiseState !== "pending") return; this.promiseState = "rejected"; this.promiseResult = err; }; try { fun(resolve, reject); } catch (error) { reject(error); }}