实现promise的catch方法和类的错误处理constPEDDING='PEDDING'constRESOLVE='RESOLVE'constREJECT='REJECT'//promise有三种状态consthandlePromise=(result,newPromise,resolve,reject)=>{if(result===newPromise){thrownewError('Cannotreturnitself')}//返回的是对象或者方法(也可以是promise)if((typeofresult==='object'&&typeofresult!==null)||typeofresult==='function'){//添加一个lock字段,如果第一个方法执行了,第二个方法就不会执行letlock=falsetry{constthen=result.thenif(typeofthen==='function'){//如果then方法是一个函数,默认是promise//调用call方法then.call(result,(r)=>{if(lock)return//继续调用自己,r是resinthenhandlePromise(r,newPromise,resolve,reject)lock=true},(e)=>{if(lock)returnreject(e)lock=true})}else{resolve(result)}}catchh(error){reject(error)}//判断result是否有then方法}else{//返回正常值resolve(result)}}classNewPromise{//初始状态为PEDDINGstatus=PEDDINGresult=undefinedreason=undefined//发布订阅者模式//目的是实现异步onResolveArr=[]onRejectArr=[]constructor(exc){constresolve=(result)=>{if(this.status===PEDDING){this.result=resultthis.status=RESOLVE//执行发布者this.onResolveArr.map((fn)=>fn())}}constreject=(reason)=>{if(this.status===PEDDING){this.reason=reasonthis.status=REJECT//执行发布者this.onRejectArr.map((fn)=>fn())}}//处理错误函数的方法try{exc(resolve,reject)}catch(error){reject(error)}}then(onResolve,onReject){//判断onResolve是否是方法onResolve=typeofonResolve==='function'?onResolve:(data)=>dataonReject=typeofonReject==='函数''?onReject:(err)=>{thrownewError('onRejectmustbeamethod'+err)}constnewPromise=newNewPromise((resolve,reject)=>{if(this.status===RESOLVE){setTimeout(()=>{尝试{constresult=onResolve(this.result)handlePromise(result,newPromise,resolve,reject)}catch(error){reject(error)}},0)}if(this.status===REJECT){setTimeout(()=>{try{constresult=onReject(this.reason)handlePromise(result,newPromise,resolve,reject)}catch(error){reject(error)}},0)}//发布订阅者模式if(this.status===PEDDING){//添加订阅者到数组this.onResolveArr.push(()=>{try{constresult=onResolve(this.result)handlePromise(result,newPromise,resolve,拒绝)}赶上(错误){reject(error)}})this.onRejectArr.push(()=>{try{constresult=this.onReject(this.reason)handlePromise(result,newPromise,resolve,reject)}catch(error){拒绝(错误)}})}})returnnewPromise}catch(onReject){//返回then方法,then是一个promise第一个参数未定义,需要在then方法中处理returnthis.then(undefined,onReject)}}//letyan=newPromise((resole,reject)=>{//resole('燕叔真帅')//})//yan.then(res=>{//console.log(res)//})letnewYan=newNewPromise((resole,reject)=>{//调用时,如果下面的方法报错,需要处理错误并提示错误Calltr??ycatchsetTimeout(()=>{newPromise类的方法中的resole('新颜大叔好帅')return'1111'},3000)})newYan.then((res)=>{//同理如果这个方法也是错误的,then方法中需要trycatchconsolelog(res)return{name:'yan'}}).then((res)=>{//Similary,如果这个方法也出错,then方法中需要trycatchconsole.log(res)console.log(res)})console.log(11111111)
