欢迎光临散文网 会员登陆 & 注册

手写Promise核心代码 - JavaScript前端Web工程师

2022-05-07 23:48 作者:江火渔枫  | 我要投稿

```

const { reject } = require("core-js/fn/promise");


class Commitment {


  static PENDING = '待定';

  static FULFILLED = '成功';

  static REJECTED = '拒绝';


  constructor(func){

    this.status = Commitment.PENDING;

    this.result = null;

    this.resolveCallbacks = [];

    this.rejectCallbacks = [];

    //***bind(this) 将this指向新创建的对象 commitment ****/

    //func(this.resolve.bind(this), this.reject.bind(this));


    //原生promise调用than 可以把错误的信息做为内容输出出来 调用方式如下

    /***

     * let promise = new Promise((resolve, reject) => {

     * throw new Error('输出错误信息');

     * })

     * ** */

    try{

      func(this.resolve.bind(this), this.reject.bind(this));

    } catch (error){

      //这里是直接执行不是创建实例后再执行 不用绑定this

      this.reject(error);

    }

  }


  resolve(){

    setTimeout(() => {

      if(this.status === Commitment.PENDING){

        this.status = Commitment.FULFILLED;

        this.result = result;

        this.resolveCallbacks.forEach(callback =>{

          callback(result)

        })

      }

    });

  }

  reject(){

    setTimeout(() => {

      if(this.status === Commitment.PENDING){

        this.status = Commitment.REJECTED;

        this.result = result;

        this.rejectCallbacks.forEach(callback => {

          callback(result)

        })

      }

    });

  }

  than(onFULFILLED, onREJECTED){

    //为实现 .than链式调用 方法内返回new Commitment

    return new Commitment((resolve, reject) => {

      // than 里面的两个参数不是函数则不被执行

      //解决思路 赋值空函数

      onFULFILLED = typeof onFULFILLED === 'function' ? onFULFILLED : () => {};

      onREJECTED = typeof onREJECTED === 'function' ? onREJECTED : () => {};

      if(this.status === Commitment.PENDING){

        this.resolveCallbacks.push(onFULFILLED);

        this.rejectCallbacks.push(onREJECTED);

      }

      if(this.status === Commitment.FULFILLED){

        onFULFILLED(this.result);

      }

      if(this.status === Commitment.REJECTED){

        onREJECTED(this.result);

      }

    })

  }

}


let commitment = new Commitment((resolve, reject) => {

  resolve('这次一定');

});

commitment.than(

  result => {console.log(result)},

  result => {console.log(result.message)}

).than(

  result => {console.log(result)},

  result => {console.log(result.message)}

);


```






手写Promise核心代码 - JavaScript前端Web工程师的评论 (共 条)

分享到微博请遵守国家法律