手写promise

it2025-01-16  5

function promise(option){ const that = this; //防止this指针的改变 that.status = 'pending'; //初始化的状态值 that.value = null; //保存外部传入的值 //创建执行resolve时的函数 function reslove(value){ if(that.status=='pending'){ that.status = 'resolve'; //改变status的状态 that.value = value; } // console.log(that) } //创建执行reject的函数也就是失败函数 function reject(value){ if(that.status == 'pending'){ that.status = 'reject'; ;//改变status的状态 that.value = value } } //可能声明了promise还在等待状态,对齐进行处理 try{ option(reslove,reject) }catch(e){ reject(e) } // option(reslove,reject) } //创建链式调用 promise.prototype.then = function(fn1,fn2){ if( this.status == 'resolve'){ fn1(this.value) }else{ fn2(this.value) } } let pro = new promise(function(res,rej){ res('123') }) // pro.then((data)=>{ // console.log(data); // }) pro.then(function(data){ console.log(data); },function(err){ console.log(err); })

 

最新回复(0)