写出自己的promise

手写promise

//excutor 为promise回调函数
function myPro(excutor) {
    this.state = 'pending';		//状态
     this.value = undefined;	//回调成功值
     this.reason = undefined;	//回调失败原因
     this.onFulfilleds = [];	//成功回调函数组
     this.onRejecteds = [];		//失败回调函数组
     resolve = value => {
     	//判断改变状态
         if(this.state == 'pending'){
             this.value = value; 	//记录回调成功值
             this.state = 'resolved'; 	//更改状态
             //触发成功回调函数,并传递回调成功值
             this.onFulfilleds.forEach(fn=>{
                 this.value = fn(this.value);
             });
         }
     }
     reject = reason => {
     	//判断改变状态
         if(this.state == 'pending'){
             this.reason = reason;	//记录失败回调值
             this.state = 'rejected';	//更改状态
             //触发失败回调函数,并传递回调失败值
             this.onRejecteds.forEach(fn=>{
                 this.reason = fn(this.reason);
             });
         }
     }
     //执行promise回调函数,传递resolve函数,reject函数
     excutor(resolve,reject);
 };
 //在原型上添加then方法
 myPro.prototype.then = function (onFulfilled,onRejected){
 	//类型判断,并加入成功回调函数组
     if(typeof onFulfilled === 'function'){
        this.onFulfilleds.push(onFulfilled);
     }
     //类型判断,并加入失败回调函数组
     if(typeof onRejected === 'function'){
        this.onRejecteds.push(onRejected);
     }
     //返回当前实例
     return this;
 };
 //创建mypro实例
 let p = new myPro((resolve,reject)=>{
     console.log('promise 执行');
     setTimeout(()=>{
         resolve(1);
         //reject('出错');
     },500);
 });
 p.then(res=>{
     console.log('成功回调:'+res);
     return res+1;
 },err=>{
     console.log('失败回调:'+err);
     return err+':出错';
 }).then(res=>{
     console.log('成功回调:'+res);
 });

输出:
promise 执行
成功回调:1
成功回调:2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值