返回

掌握Promise函数自定义封装技巧,精通异步编程!

前端

前言

在现代前端开发中,异步编程已成为不可或缺的一部分,而Promise函数则是异步编程中的利器。Promise函数可以帮助我们轻松处理异步操作,让代码更加简洁、可读性更强。然而,原生Promise函数的功能有限,因此,我们常常需要对Promise函数进行自定义封装,以满足更复杂的异步编程需求。

Promise函数简介

Promise函数是一个 JavaScript 内置对象,它代表了一个异步操作的最终完成或失败的结果。我们可以通过Promise函数来处理异步操作,而无需使用回调函数。Promise函数提供了三个状态:

  • Pending:等待执行
  • Fulfilled:执行成功
  • Rejected:执行失败

自定义封装Promise函数

原生Promise函数的功能有限,因此,我们常常需要对Promise函数进行自定义封装,以满足更复杂的异步编程需求。自定义封装Promise函数的步骤如下:

  1. 定义一个Promise构造函数
  2. 在构造函数中添加resolve和reject方法
  3. 在构造函数中添加then方法
  4. 在构造函数中添加catch方法
  5. 在构造函数中添加finally方法

自定义封装Promise函数示例

function Promise(executor) {
  this.state = "pending";
  this.value = null;
  this.reason = null;
  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 = (reason) => {
    if (this.state === "pending") {
      this.state = "rejected";
      this.reason = reason;
      this.onRejectedCallbacks.forEach((callback) => {
        callback(this.reason);
      });
    }
  };

  executor(resolve, reject);
}

Promise.prototype.then = function (onFulfilled, onRejected) {
  return new Promise((resolve, reject) => {
    if (this.state === "fulfilled") {
      setTimeout(() => {
        try {
          const value = onFulfilled(this.value);
          resolve(value);
        } catch (error) {
          reject(error);
        }
      }, 0);
    } else if (this.state === "rejected") {
      setTimeout(() => {
        try {
          const reason = onRejected(this.reason);
          resolve(reason);
        } catch (error) {
          reject(error);
        }
      }, 0);
    } else {
      this.onFulfilledCallbacks.push(() => {
        setTimeout(() => {
          try {
            const value = onFulfilled(this.value);
            resolve(value);
          } catch (error) {
            reject(error);
          }
        }, 0);
      });

      this.onRejectedCallbacks.push(() => {
        setTimeout(() => {
          try {
            const reason = onRejected(this.reason);
            resolve(reason);
          } catch (error) {
            reject(error);
          }
        }, 0);
      });
    }
  });
};

Promise.prototype.catch = function (onRejected) {
  return this.then(null, onRejected);
};

Promise.prototype.finally = function (onFinally) {
  return this.then(
    (value) => {
      onFinally();
      return value;
    },
    (reason) => {
      onFinally();
      throw reason;
    }
  );
};

结语

通过对Promise函数的自定义封装,我们可以轻松处理更复杂的异步编程需求,让代码更加简洁、可读性更强。掌握Promise函数自定义封装技巧,将帮助您成为异步编程高手!