模拟实现 promise (搬运篇)

196 阅读1分钟

基本的版本

  • 设定三个状态 PENDING,FULFILLED, REJECTED, 只能由 PENDING改变为FULFILLEDREJECTED, 并且只能改变一次
  • myOPrimise() 接受一个函数 exector, executor有两个参数 resolve方法和 reject 方法
  • resolvePENDING 改变为 FULFILLED
  • rejectPENDING 改变为 FULFILLED
  • promise 变为 FULFILLED 状态后具有唯一的value
  • promise 变为 REJECTED 状态后具有唯一的 reason
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

function MyOPrimise(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);
    }
}