//简单版promise//第一步:列出三大块this.thenresolve/rejectfn(resolve,reject)//第二步:this.then负责注册所有函数resolve/reject负责执行所有函数//第三步:给resolve/reject加上setTimeout,防止resolve在注册then之前直接执行//第四步:在resolve/reject中返回这个,这样就可以进行链式调用//前五步:三种状态的管理pendingfulfilledrejected//*****promise链调用在then中返回一个promise,以便可以将异步函数添加到then//添加catch函数PromiseM(fn){varvalue=null;变种回调=[];//加入状态解决Promise异步操作成功后then注册的回调不会执行的问题varstate='pending';var_this=这个;//注册所有的回调函数this.then=function(fulfilled,rejected){//如果要链式promise,必须在这里返回一个新的PromisereturnnewPromiseM(function(resolv,reject){//异常处理try{if(state=='pending'){callbacks.push(fulfilled);//实现链式调用返回;}if(state=='fulfilled'){vardata=fulfilled(value);//为了连接两个promiseresolv(data);返回;}if(state=='rejected'){vardata=rejected(value);//为了连接两个promiseresolv(data);返回;}}catch(e){_this.catch(e);}});}//执行所有回调函数functionresolve(valueNew){value=valueNew;state='已完成';执行();}//执行所有回调函数functionreject(valueNew){value=valueNew;状态='拒绝';执行();}functionexecute(){//添加延迟机制,防止promise中的同步函数导致resolve在函数注册前先执行setTimeout(function(){callbacks.forEach(function(cb){value=cb(value);});},0);}this.catch=function(e){console.log(JSON.stringify(e));}//异步回调的经典实现fn(resolve,reject);}
