手动实现一个promise

  1. Promise的参数是一个函数,这个函数有2个参数,分别是resolve 和reject
  2. Promise的状态一开始是pending,满足某些条件是,状态变为resolved, 不满足某些条件时,状态变为rejected
  3. 通常通过将Promise作为一个构造函数,通过new 进行调用
  4. 会在then()中接收,resolve 和reject的返回信息

1、基础版

   function Promise_(foo){ // foo是一个函数,它有两个参数resolve,reject
      this.status="pending"; // 初始状态,status 是pending的
      this.resolveData; // 保存 resolve 时的返回值
      this.rejectData;  // 保存 reject 时的返回值
      var _this=this; // 暂存this,否则在resolve 和reject中的this指向是不对滴...
      var resolve=function(data){
         if(_this.status=="pending"){
            _this.status="resolved";// 修改状态
            _this.resolveData=data; 
         }
      }
      var reject=function(data){
         if(_this.status=="pending"){
            _this.status="rejected";
            _this.rejectData=data;
         }
      }
      foo(resolve,reject);
   }
   Promise_.prototype.then=function(resolveCallback,rejectCallback){
      if(this.status=="resolved"){
        resolveCallback(this.resolveData);
      }
      if(this.status=="rejected"){
         rejectCallback(this.rejectData);
      }
   }

  const pp=new Promise_((resolve,reject)=>{
     if(12>10){
        resolve("大禹10");
     }else{
        reject("小于等于10");
     }
  })
  pp.then(res=>{
     console.log(res,"----------xu  xu")
  })

在这里插入图片描述

这样,一个最最基本的promise实现了,测试了下是可以正常执行的。
但是有个问题。。。。。。。很多时候不是resolve不是同步进行的。比如定时器。ajax请求之类的操作结束之后才 resolve,改变promise的状态。。。。。。。。。。

2、使用定时器实现异步

目前想到的解决方式是:async await 或者定时器

2.1 定时器 方法实现

改写then方法。当this.status=="pending"时一直不停的调用自身,直到this.status的状态改变。改变之后,执行then的回调函数resoveCallback或者rejectCallback

        Promise_.prototype.then =  function (resolveCallback, rejectCallback) {
            var _this = this;
            if (this.status === "resolved") {
                resolveCallback(this.resolveValue)
            }
            if (this.status === "rejected") {
                rejectCallback(this.rejectValue)
            }
            if (this.status === "pending") {
                var se = setInterval(function () {
                    if (_this.status === "resolved") {
                        resolveCallback(_this.resolveValue);
                        clearInterval(se);
                    }
                    if (_this.status === "rejected") {
                        rejectCallback(_this.rejectValue)
                        clearInterval(se);
                    }
                }, 50)   
            }
        }

异步 修改promise的状态

  setTimeout(function () {
                    resolve("大于10");                 
                }, 3000)

测试了一下,基本符合了要求,同步的部分直接打印。而resolve的部分则在3秒之后 打印。。。。
在这里插入图片描述

不知道为毛。。。感觉怪怪的。。。。。。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值