一、Executor中异步操作的处理
executor中异步操作,then方法中callbacks需要在promise.status改变后再执行
二、then方法的多次调用
多次调用then方法,callbacks会按照顺序来执行。
此处用到了发布订阅模式,收集then方法中回调时用到了订阅,resolve和reject方法执行时用到了发布。
const PENDING = 'pending';const FULFILLED = 'fulfilled';const REJECTED = 'rejected';class MPromise{constructor(excuter){this.status = PENDING;this.value = undefined;this.reason = undefined;this.onFulfilledCallbacks = []this.onRejectedCallbacks = []//声明resole和reject函数,这里用箭头函数可以避免this指向改变,单独方法调用,this指向window或undefinedconst resolve = (val) =>{if(this.status === PENDING){this.value = valthis.status = FULFILLEDthis.onFulfilledCallbacks.forEach((fn)=> fn())}}const reject = (reason) =>{if(this.status === PENDING){this.reason = reasonthis.status = REJECTEDthis.onRejectedCallbacks.forEach((fn)=> fn())}}try{executor(resolve, reject)}catch(error){reject(error)}}//then方法核心部分是,判断promise当前status,做出不同操作//function class里面添加原型方法,不用写function关键字then(onFulfilled, onRejected){//如果是pending状态,收集相关方法,等状态改变时再调用if(this.status === PENDING){//之前搜集回调时,没有传value和reasonthis.onFulfilledCallbacks.push(()=>{onFulfilled(this.value)})this.onRejectedCallbacks.push(()=>{onRejected(this.reason)})}if(this.status === FULFIILED){onFulfilled(this.value)}if(this.status === REJECTED){onRjected(this.reason)}}}
