一、基础版
手写方法时,根据功能来添加代码,不要死记代码
let myPromise = new Promise((resolve, reject)=>{setTimeout(()=>{resolve('resolved')},1000)});myPromise.then((res)=>{},(reason)=>{}).catch((error)=>{});function MPromise(excutor){//创建的promise状态为pendingthis.PromiseState = 'pending';this.PromiseResult = null;//判断resolve和reject接受参数是不是promise对象的方法this.checkPromise = function(item){//粗略判断是否有then方法return typeof item === 'function'}//创建给excutor传入的resolve和reject方法function resolve(param){let isPromise = param && this.checkPromise(param);//判断resolve处理的是否为promise,如果是的话,promise的状态由resolve处理的promise决定if(!isPromise){console.log('change PromiseState')this.PromiseState = 'fullfilled'this.PromiseResult = param}else{console.log('isPromise')//如果是promise,等参数promise状态改变后调用起then方法,//将resolve和reject方法传进入then回调函数,fullfilled时调用resolve,rejected时调用rejectparam.then(resolve,this.reject)}}function reject(param){this.PromiseState = 'rejected'this.PromiseResult = param}//(1)then方法,可以根据promise状选择性执行传入函数//(2)根据参数函数执行结果返回值,创建新的promise并返回//次函数有两个功能,为了解耦,将每个功能写为独立的函数this.callBackHandler = function (handler){let currentPromiseState = this.PromiseState,promiseResult = this.PromiseResult,handlerResult;if(currentPromiseState === 'fullfilled'){handlerResult = handler.onResolved(promiseResult)}else if(currentPromiseState === 'rejected'){handlerResult = handler.onrejected(promiseResult)}console.log('handlerResult', handlerResult)return handlerResult}this.createNewPromise = function (handlerResult){//先判断是否为promise,如果不是则创建一个新promiselet isPromise = this.checkPromise(handlerResult);if(isPromise) return handlerResultreturn new MPromise((resolve)=>{resolve(handlerResult)})}//this.then = function(cb1,cb2){// const currentPromiseState = this.PromiseState,// promiseResult = this.PromiseResult// if(currentPromiseState === 'fullfilled'){// cb1(promiseResult)// }else if(currentPromiseState === 'rejected'){// cb2(promiseResult)// }//}this.then = function(cb1,cb2){//先执行回调函数,并保存返回值let handler = {onResolved : cb1,onrejected : cb2},promiseResult = this.callBackHandler(handler),newPromise = this.createNewPromise(promiseResult);return newPromise}this.catch = function(cb){判断promiseState是否为rejected,才执行catch的回调函数//先执行回调函数,并保存返回值let handler = {onrejected : cb},promiseResult = this.callBackHandler(handler),newPromise = this.createNewPromise(promiseResult);return newPromise}//给excutor函数提供两个函数方法参数,然后执行excutor(resolve.bind(this),reject.bind(this))}let myPromise = new MPromise((resolve, reject)=>{setTimeout(()=>{resolve('resolved')},1000)});myPromise.then((res)=>{console.log(res)},(reason)=>{console.log(reason)}).catch((error)=>{})
