美文网首页
JS中Promise的类式实现写法

JS中Promise的类式实现写法

作者: 硅谷干货 | 来源:发表于2024-03-09 17:30 被阅读0次

    Promise在面试中也会经常遇到,以下是我的手写实现方式,经测试效果不错,小伙伴们们可以直接拷贝使用。

    类式定义方式

    class MyPromise {
      constructor(executor) {
        this.status = "pending";
        this.value = undefined;
        this.reason = undefined;
    
        let resolveFn = (value) => {
          if (this.status === "pending") {
            this.status = "resolve";
            this.value = value;
          }
        };
    
        let rejectFn = (reason) => {
          if (this.status === "pending") {
            this.status = "reject";
            this.reason = reason;
          }
        };
    
        try {
          executor(resolveFn, rejectFn);
        } catch (error) {
          rejectFn(error);
        }
      }
    
      then(onFulfilled, onRejected) {
        if (this.status === "resolve") {
          onFulfilled(this.value);
        }
        if (this.status === "reject") {
          onRejected(this.reason);
        }
      }
    }
    

    测试和打印

    new MyPromise((resolve, reject) => {
      resolve("123");
    }).then((res) => {
      console.log(res);
    });
    

    输出如下:

    image.png

    相关文章

      网友评论

          本文标题:JS中Promise的类式实现写法

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