手写Promise,实现then和catch方法

手写 Promise 类,包含 then 方法和 catch 方法:

class MyPromise {
  constructor(executor) {
    this.state = 'pending';
    this.value = undefined;
    this.error = undefined;
    this.onFulfilledCallbacks = [];
    this.onRejectedCallbacks = [];

    const resolve = (value) => {
      if (this.state === 'pending') {
        this.state = 'fulfilled';
        this.value = value;
        this.onFulfilledCallbacks.forEach((callback) => callback(this.value));
      }
    };

    const reject = (error) => {
      if (this.state === 'pending') {
        this.state = 'rejected';
        this.error = error;
        this.onRejectedCallbacks.forEach((callback) => callback(this.error));
      }
    };

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

  then(onFulfilled, onRejected) {
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (value) => value;
    onRejected = typeof onRejected === 'function' ? onRejected : (error) => { throw error; };

    return new MyPromise((resolve, reject) => {
      const handleFulfilled = () => {
        setTimeout(() => {
          try {
            const result = onFulfilled(this.value);
            resolve(result);
          } catch (error) {
            reject(error);
          }
        });
      };

      const handleRejected = () => {
        setTimeout(() => {
          try {
            const result = onRejected(this.error);
            resolve(result);
          } catch (error) {
            reject(error);
          }
        });
      };

      if (this.state === 'fulfilled') {
        handleFulfilled();
      } else if (this.state === 'rejected') {
        handleRejected();
      } else if (this.state === 'pending') {
        this.onFulfilledCallbacks.push(handleFulfilled);
        this.onRejectedCallbacks.push(handleRejected);
      }
    });
  }

  catch(onRejected) {
    return this.then(undefined, onRejected);
  }
}

这个手写的 Promise 类包含 then 方法和 catch 方法,并且能够正常处理 Promise 的链式调用和异常捕获。

测试示例:

const promise = new MyPromise((resolve, reject) => {
  // 异步操作
  setTimeout(() => {
    resolve('Promise resolved');
    // reject(new Error('Promise rejected'));
  }, 1000);
});

promise
  .then((data) => {
    console.log(data); // 输出:Promise resolved
    return 'New data';
  })
  .then((data) => {
    console.log(data); // 输出:New data
    throw new Error('Custom error');
  })
  .catch((error) => {
    console.error(error); // 输出:Custom error
  });

在上面的例子中,我们创建了一个简单的 Promise,并通过 then 方法链式调用,然后使用 catch 方法捕获异常。

全部评论

相关推荐

在秋招的河老师很爱吃:40岁失业 假如22岁开始工作 18年前 2007年那个时候如何 2015年开始互联网爆发 这个时候有了8年经验 然后黄金10年 你想想这些年挣了多少 这要是进的时候某个大厂 这辈子根本花不完了
你找实习最大的坎坷是什么
点赞 评论 收藏
分享
敢逐云霄志:你打招呼语怎么能这么长,hr都没看下去的欲望,简明扼要说重点,就读于某某学校某某专业,26届应届毕业生,学信网可查,先后在某某公司实习过(如有),然后做过什么项目,想找一份什么样的工作,可实习几个月以上,期待您的回复。
点赞 评论 收藏
分享
11-15 16:33
已编辑
微软_sde(实习员工)
点赞 评论 收藏
分享
评论
3
6
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务