美文网首页让前端飞Web前端之路
实现一个Promise之基础、异步

实现一个Promise之基础、异步

作者: wade3po | 来源:发表于2020-03-12 17:02 被阅读0次

    其实跟着promise a+一步一步,按照顺序实现一个promise并不难,今天先实现最简单的promise和异步resolve。本来想全部一次性写完,想想还是分开走,希望想学的可以敲几遍。

    //promise三个状态
    
    const PENDING = 'PENDING';
    
    const FULFILLED = 'FULFILLED';
    
    const REJECTED = 'REJECTED';
    
    
    
    class Promise {
    
     constructor(executor){
    
      //状态
    
      this.state = PENDING;
    
      //成功值 失败值 默认undefined
    
      this.value = undefined;
    
      this.reason = undefined;
    
      //简易发布订阅,实例可以then多次,用数组
    
      this.onResolvedCallbacks = [];
    
      this.onRejectedCallbacks = [];
    
      
    
      //成功方法
    
      let resolve = (value) => {
    
       if(this.state === PENDING){
    
        this.state = FULFILLED;
    
        this.value = value;
    
        this.onResolvedCallbacks.forEach(fn => fn());
    
       }
    
      };
    
      
    
      //失败方法
    
      let reject = (reason) => {
    
       if(this.state === PENDING){
    
        this.state = REJECTED;
    
        this.reason = reason;
    
        this.onRejectedCallbacks.forEach(fn => fn());
    
       }
    
      };
    
      
    
      //立即执行,如果有错误直接执行失败方法
    
      try{
    
       executor(resolve, reject);
    
      }catch (e) {
    
       reject(e);
    
      }
    
     }
    
     //then方法,一个成功函数,一个失败函数
    
     then(onFulfilled, onRejected){
    
      //如果成功,执行成功函数
    
      if(this.state === FULFILLED){
    
       onFulfilled(this.value);
    
      };
    
      
    
      //如果失败,执行失败函数
    
      if(this.state === REJECTED){
    
       onRejected(this.reason);
    
      };
    
      
    
      //如果有异步,订阅成功失败函数
    
      if(this.state === PENDING){
    
       this.onResolvedCallbacks.push(() => {
    
        onFulfilled(this.value);
    
       });
    
       
    
       this.onRejectedCallbacks.push(() => {
    
        onRejected(this.reason);
    
       });
    
      };
    
     }
    
    }
    

    最简单的实现,可以理解理解。

    image

    相关文章

      网友评论

        本文标题:实现一个Promise之基础、异步

        本文链接:https://www.haomeiwen.com/subject/wjumjhtx.html