美文网首页
手写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

    手写 Promise 我们会通过手写一个符合 Promise/A+ 规范的 Promise 来深入理解它,并且手写...

  • 手写 Promise 系列 --- 3

    在前两篇(手写 Promise 系列 --- 1)和(手写 Promise 系列 ---2) 中,达成了3个目标 ...

  • 手写Promise

    $ 正常的promise用法   $ 手写的Promise   # 测试可行性

  • 手写promise

    手写promise 带大家手写一个 promis。在手写之前我会先简单介绍一下为什么要使用promise、prom...

  • 纯手写实现自己的nodejs promise 库

    纯手写实现自己的nodejs promise 库什么是Promise?promise 链Async/Await后续...

  • 手写基础 promise

    1. 前言 玩下吧 手写 promise,看看能写成啥样 2. promise 基础结构 3. 手写`promi...

  • 手写 Promise

    一、Promise 是一个异步操作返回的对象,用来传递异步操作的消息。 Promise 介绍和使用详见: 认识并使...

  • 手写Promise

  • 手写Promise

    Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。 这篇博客有关于P...

  • 手写promise

    本章节纯粹是对promise手写实现。如果不了解promise自行了解再来学习本章知识。promise初体验首先,...

网友评论

      本文标题:手写Promise

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