Skip to content

手撕promise(二) #45

Open
Open
@coderInwind

Description

@coderInwind

手撕promise

const STATUS_PENDING = "pending";
const STATUS_RESOLVE = "fulfilled";
const STATUS_REJECT = "rejected";

class Mypromise {
  constructor(executor) {
    this.status = STATUS_PENDING;
    this.value = null;
    this.reason = null;

    const resolve = (value) => {
      if (this.status === STATUS_PENDING) {
        queueMicrotask(()=>{
          this.status === STATUS_RESOLVE;
          this.value = value;
          this.onFulfilled(this.value);
        })
      }
    };
    const reject = (value) => {
      if (this.status === STATUS_PENDING) {
        queueMicrotask(()=>{
          this.status === STATUS_REJECT;
          this.value = value;
          this.onReject(this.value);
        })
      }
    };
    executor(resolve, reject);
  }

  then(onFulfilled, onReject) {
    this.onFulfilled = onFulfilled;
    this.onReject = onReject;
  }
}

const promise = new Mypromise((resolve, reject) => {
    resolve("测试resolve")
    reject("测试reject")
});

promise.then(
  (res) => {
    console.log(res);
  },
  (err) => {
    console.log(err);
  }
);

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions