constPEDDING='PEDDING';constRESOLVE='RESOLVE';constREJECT='REJECT';//promise有三种状态classNewPromise{//初始状态为PEDDINGstatus=PEDDINGresult=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())}}exc(resolve,reject)}then(onResolve,onReject){if(this.status===RESOLVE){setTimeout(()=>{onResolve(this.result)},0)}if(this.status===REJECT){setTimeout(()=>{onReject(this.reason)},0)}//发布订阅者模式if(this.status===PEDDING){//添加订阅者到数组this.onResolveArr.push(()=>{onResolve(this.result)})this.onRejectArr.push(()=>{this.onReject(this.reason)})}}}//letyan=newPromise((resole,reject)=>{//resole('颜叔好帅')//})//yan.then(res=>{//console.log(res)//})letnewYan=newNewPromise((resole,reject)=>{setTimeout(()=>{resole('新颜好帅')},3000)})newYan.then(res=>{console.log(res)})console.log(11111111)
