美文网首页
手写Promise

手写Promise

作者: Victor_818 | 来源:发表于2019-10-28 18:26 被阅读0次

    1. 简易版Promise,只能调用一次then,不能链式调用:

    class Promise {
      constructor(executor) {
        this.status = 'pending';
        this.value = undefined;
        this.reson = undefined;
        // 成功存放的数组
        this.onResolvedCallbacks = [];
        // 失败存放法数组
        this.onRejectedCallbacks = [];
        // 成功时调用
        let resolve = value => {
          setTimeout(() => {
            if (this.status === 'pending') {
              this.status = 'fulfilled';
              this.value = value;
              // 一旦resolve执行,调用成功数组的函数
              this.onResolvedCallbacks.forEach(fn => {
                fn();
              });
            }
          });
        };
        // 失败时调用
        let reject = reson => {
          setTimeout(() => {
            if (this.status === 'pending') {
              this.status = 'rejected';
              this.reson = reson;
              // 一旦reject执行,调用失败数组的函数
              this.onRejectedCallbacks.forEach(fn => {
                fn();
              });
            }
          });
        };
    
        try {
          executor(resolve, reject);
        } catch (error) {
          reject(error);
        }
      }
      then(onFulfilled, onRejected) {
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
        onRejected =
          typeof onRejected === 'function'
            ? onRejected
            : err => {
                throw err;
              };
        setTimeout(() => {
          if (this.status === 'fulfilled') {
            onFulfilled(this.value);
          }
        });
        setTimeout(() => {
          if (this.status === 'rejected') {
            onRejected(this.reson);
          }
        });
        if (this.status === 'pending') {
          this.onResolvedCallbacks.push(() => {
            setTimeout(() => {
              onFulfilled(this.value);
            });
          });
          this.onRejectedCallbacks.push(() => {
            setTimeout(() => {
              onRejected(this.reson);
            });
          });
        }
      }
    }
    let premise = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('0.123');
      });
    });
    premise.then(res => {
      console.log(res); // 0.123
    });
    
    

    相关文章

      网友评论

          本文标题:手写Promise

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