首页 > 代码库 > Promise简单实现
Promise简单实现
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=http://www.mamicode.com/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简单实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。