promise解决的问题 --自己的一次学习

// 1) 解决并发问题 (同步多个异步方法的执行结果)
// 2) 链式调用的问题 (现获取 name,通过name在获取age) 解决多个回调嵌套的问题


// Promise是一个类  可以按照这个思路手写promise
// 1)每次new 一个Promise 都需要传递一个执行器 ,执行器是立即执行的
// 2) 执行器函数中有两个参数 resolve,reject

// 3)默认Promise 有三个状态 pendding =》 resolve 表示成功了fulfilled reject就是拒绝 rejected
// 4) 如果一旦成功了 不能变成失败 一旦失败 不能在成功了 只有当前状态是pending的时候 才能更改状态
// 5) 每个promise都有一个then方法
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";
class Promise {
  constructor(executor) { // executor 执行器
    // 创建promise executor会立即执行
    this.value = undefined;
    this.reason = undefined;
    this.status = PENDING;
    let resolve = value => {
      if (this.status === PENDING) {
        this.value = value;
        this.status = FULFILLED;
      }
    };
    let reject = reason => {
      if (this.status === PENDING) {
        this.reason = reason;
        this.status = REJECTED;
      }
    };
    // 这里可能会发生异常
    try {
      executor(resolve, reject);
    } catch (e) {
      reject(e);
    }
  }

  // then方法会判断当前的状态
  then(onFulfilled, onRejected) {
    if (this.status === FULFILLED) {
      onFulfilled(this.value);
    }
    if (this.status === REJECTED) {
      onRejected(this.reason);
    }
  }
}

// 导出当前类 commonjs定义方式
module.exports = Promise;
// 链式调用


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值