【JS】手写promise方法

function MyPromise(executor) {
  // 初始状态为 Pending
  this.status = 'pending';
  
  // 用于保存 resolve 和 reject 的值
  this.value = undefined;
  this.reason = undefined;
  
  // 用于存储成功和失败的回调函数
  this.onResolvedCallbacks = [];
  this.onRejectedCallbacks = [];
  
  // 定义 resolve 函数
  const resolve = (value) => {
    // 只有在状态为 Pending 时才能执行 resolve
    if (this.status === 'pending') {
      // 将状态改为 Resolved
      this.status = 'resolved';
      
      // 保存 resolve 的值
      this.value = value;
      
      // 执行成功的回调函数
      this.onResolvedCallbacks.forEach(callback => callback());
    }
  };
  
  // 定义 reject 函数
  const reject = (reason) => {
    // 只有在状态为 Pending 时才能执行 reject
    if (this.status === 'pending') {
      // 将状态改为 Rejected
      this.status = 'rejected';
      
      // 保存 reject 的原因
      this.reason = reason;
      
      // 执行失败的回调函数
      this.onRejectedCallbacks.forEach(callback => callback());
    }
  };
  
  // 执行传入的 executor 函数,并传入 resolve 和 reject 函数
  try {
    executor(resolve, reject);
  } catch (error) {
    // 如果执行过程中发生异常,将其作为 reject 的原因处理
    reject(error);
  }
}

// 添加 then 方法
MyPromise.prototype.then = function(onFulfilled, onRejected) {
  if (this.status === 'resolved') {
    // 如果状态为 Resolved,执行成功回调函数
    onFulfilled(this.value);
  } else if (this.status === 'rejected') {
    // 如果状态为 Rejected,执行失败回调函数
    onRejected(this.reason);
  } else if (this.status === 'pending') {
    // 如果状态为 Pending,将成功和失败的回调函数保存起来
    this.onResolvedCallbacks.push(() => {
      onFulfilled(this.value);
    });
    this.onRejectedCallbacks.push(() => {
      onRejected(this.reason);
    });
  }
};

// 示例用法
const myPromise = new MyPromise((resolve, reject) => {
  // 异步操作,比如 setTimeout
  setTimeout(() => {
    // 模拟异步操作成功,调用 resolve
    resolve('成功的结果');
  }, 1000);
});

// 使用 then 方法处理成功和失败的情况
myPromise.then(
  result => {
    console.log('成功:', result);
  },
  reason => {
    console.log('失败:', reason);
  }
);
  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值