基于INSCODE AI 手写Promise

文章介绍了如何创建一个基本的Promise类,包括构造函数接收executor参数,内部管理状态(state)和结果(result),以及resolve和reject函数来改变状态和执行回调。then方法用于添加成功和失败的回调处理。
摘要由CSDN通过智能技术生成
Promise 是一个表示异步操作完成或失败的对象。实现一个简单的 Promise,可以按照以下步骤进行:
  1. 定义 Promise 函数,它接受一个 executor 函数作为参数。
  2. 在 Promise 函数内部,定义初始状态为‘Pending’,初始值为 undefined 的变量 result,以及保存所有成功回调函数和失败回调函数的数组。
  3. 定义 resolve 和 reject 函数,分别用于改变 Promise 对象的状态和结果值,并执行对应的回调函数。
  4. 在 executor 函数内部调用 resolve 和 reject 函数,并将异步操作的结果作为参数传递给它们。
  5. 定义 then 函数,它接受两个回调函数作为参数,分别用于处理 Promise 对象的状态为 resolved 或 rejected 的情况。
  6. 将 then 函数内部的回调函数加入到保存成功回调和失败回调的数组中。

以下是一个简单的实现:

class MyPromise {
  constructor(executor) {
    this.state = 'pending';
    this.result = undefined;
    this.successCallbacks = [];
    this.errorCallbacks = [];

    const resolve = value => {
      if (this.state === 'pending') {
        this.state = 'resolved';
        this.result = value;
        this.successCallbacks.forEach(callback => callback(this.result));
      }
    }

    const reject = reason => {
      if (this.state === 'pending') {
        this.state = 'rejected';
        this.result = reason;
        this.errorCallbacks.forEach(callback => callback(this.result));
      }
    }

    try {
      executor(resolve, reject);
    } catch (error) {
      reject(error);
    }
  }

  then(successCallback, errorCallback) {
    if (this.state === 'resolved') {
      successCallback(this.result);
    } else if (this.state === 'rejected') {
      errorCallback(this.result);
    } else {
      this.successCallbacks.push(successCallback);
      this.errorCallbacks.push(errorCallback);
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值