1. 程式人生 > >Promise簡單實現

Promise簡單實現

prot aso argument con reject turn prototype rom fun

 1 function Promise(fn)
 2 {
 3     this._resolvefun=null;
 4     this._rejectfun=null;
 5     this.status="pending";
 6     this.value="";
 7     this.reason="";
 8     var bind=function(ctx,fun){
 9       return function(){
10         fun.apply(ctx,arguments);
11       }
12     }
13     fn(bind(this
,this.resolve), bind(this,this.reject)); 14 } 15 Promise.prototype["resolve"]=function(value){ 16 if(this.status!="pending") return; 17 this.status="fulfilled"; 18 this.value=value; 19 this._resolvefun&&this._resolvefun(this.value); 20 } 21 22 Promise.prototype["reject"]=function
(reason){ 23 if(this.status!="pending") return; 24 this.status="rejected"; 25 this.reason=reason; 26 this._rejectfun&&this._rejectfun(this.reason); 27 } 28 29 Promise.prototype["then"]=function(onFulfilled, onRejected){ 30 if(this.status!="pending") return
; 31 this._resolve=onFulfilled; 32 this._reject=onRejected; 33 return this; 34 } 35 36 new Promise(function(resolve, reject) { 37 console.log("b"); 38 //setTimeout(resolve, 10, ‘done‘); 39 setTimeout(reject, 10, ‘done‘); 40 }).then((value) => { 41 console.log(value); 42 },(value) => { 43 console.log(value); 44 });

Promise簡單實現