1. 自定义 Promise 的构造函数:
function MyPromise(executor) {
  this.status = "pending";
  this.value = undefined;
  this.reason = undefined;
  this.onResolvedCallbacks = [];
  this.onRejectedCallbacks = [];

  const resolve = (value) => {
    if (this.status === "pending") {
      this.status = "resolved";
      this.value = value;
      this.onResolvedCallbacks.forEach((fn) => fn());
    }
  };

  const reject = (reason) => {
    if (this.status === "pending") {
      this.status = "rejected";
      this.reason = reason;
      this.onRejectedCallbacks.forEach((fn) => fn());
    }
  };

  try {
    executor(resolve, reject);
  } catch (error) {
    reject(error);
  }
}
  1. 设计后续的实验步骤:
MyPromise.prototype.then = function (onResolved, onRejected) {
  onResolved = typeof onResolved === "function" ? onResolved : (value) => value;
  onRejected =
    typeof onRejected === "function"
      ? onRejected
      : (reason) => {
          throw reason;
        };

  const promise2 = new MyPromise((resolve, reject) => {
    if (this.status === "resolved") {
      setTimeout(() => {
        try {
          const x = onResolved(this.value);
          this.resolvePromise(promise2, x, resolve, reject);
        } catch (error) {
          reject(error);
        }
      }, 0);
    }

    if (this.status === "rejected") {
      setTimeout(() => {
        try {
          const x = onRejected(this.reason);
          this.resolvePromise(promise2, x, resolve, reject);
        } catch (error) {
          reject(error);
        }
      }, 0);
    }

    if (this.status === "pending") {
      this.onResolvedCallbacks.push(() => {
        setTimeout(() => {
          try {
            const x = onResolved(this.value);
            this.resolvePromise(promise2, x, resolve, reject);
          } catch (error) {
            reject(error);
          }
        }, 0);
      });

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

  return promise2;
};

MyPromise.prototype.resolvePromise = function (
  promise2,
  x,
  resolve,
  reject
) {
  if (promise2 === x) {
    reject(new TypeError("Chaining cycle detected for promise"));
  }

  let called = false;

  if (x !== null && (typeof x === "object" || typeof x === "function")) {
    try {
      const then = x.then;

      if (typeof then === "function") {
        then.call(
          x,
          (y) => {
            if (called) return;
            called = true;
            this.resolvePromise(promise2, y, resolve, reject);
          },
          (r) => {
            if (called) return;
            called = true;
            reject(r);
          }
        );
      } else {
        resolve(x);
      }
    } catch (error) {
      if (called) return;
      called = true;
      reject(error);
    }
  } else {
    resolve(x);
  }
};

MyPromise.prototype.catch = function (onRejected) {
  return this.then(undefined, onRejected);
};

MyPromise.resolve = function (value) {
  return new MyPromise((resolve) => {
    resolve(value);
  });
};

MyPromise.reject = function (reason) {
  return new MyPromise((resolve, reject) => {
    reject(reason);
  });
};

MyPromise.all = function (promises) {
  return new MyPromise((resolve, reject) => {
    const result = [];
    let count = 0;

    for (let i = 0; i < promises.length; i++) {
      promises[i].then(
        (value) => {
          result[i] = value;
          count++;

          if (count === promises.length) {
            resolve(result);
          }
        },
        (reason) => {
          reject(reason);
        }
      );
    }
  });
};

MyPromise.race = function (promises) {
  return new MyPromise((resolve, reject) => {
    for (let i = 0; i < promises.length; i++) {
      promises[i].then(
        (value) => {
          resolve(value);
        },
        (reason) => {
          reject(reason);
        }
      );
    }
  });
};
  1. 编写一段测试代码:
const promise = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve("success");
  }, 1000);
});

promise
  .then(
    (value) => {
      console.log(value);
      return "hello";
    },
    (reason) => {
      console.log(reason);
    }
  )
  .then(
    (value) => {
      console.log(value);
    },
    (reason) => {
      console.log(reason);
    }
  );
``
1 先创建 promise 的构造函数该构造函数有一个参数这个参数是个函数我们一般叫执行函数 executor function;为执行函数再创建两个参数这两个参数也是函数作用是可以改变 promise 的状态。 2 设计后续的实验步骤让自定义对象能模拟实现 Promise 的功能包括: 1 三种状态:pending-等待 resolve-成功 reject-失败 其中最开始为pending 状态

原文地址: https://www.cveoy.top/t/topic/cuKv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录