简单版手写Promise

class _Promise {
  constructor(executor) {
    if (typeof executor !== "function") {
      throw new Error("is a not function");
    }

    this.reason = undefined;
    this.value = undefined;
    this.state = "pending";
    const resolve = (value) => {
      if (this.state == "pending") {
        this.value = value;
        this.state = "fulfilled";
      }
    };
    const reject = (reason) => {
      if (this.state == "pending") {
        this.reason = reason;
        this.state = "rejected";
      }
    };
    executor(resolve, reject);
  }

  then(onFulfilled, onRejected) {
    if (typeof onFulfilled !== "function") {
      onFulfilled = (value) => value;
    }
    if (typeof onRejected !== "function") {
      onRejected = (reason) => reason;
    }
    if (this.state == "fulfilled") {
      onFulfilled(this.value);
    }
    if (this.state == "rejected") {
      onRejected(this.reason);
    }
  }
}


new _Promise((resolve, reject) => {
  resolve(45);
}).then((res) => {
  console.log(res);
});

你可能感兴趣的:(javascript,前端)