[Untitled] JavaScript Handwriting Series (3) - Promise

foreword

PromiseIt is also a question that is often tested in interviews, and it is often used in daily work, but if I really want to talk about it, I really can’t say it, so here I directly screenshot Ruan Yifeng ’s definition of "#ECMAScript 6 Getting Started" :

insert image description here

PromiseFor the three states: Pending、fullfiled、reject, the two characteristics state changes are not affected by the outside world , once the state changes, it will not change again, and this result can be obtained at any time. Next, I will bring my eldest sister to realize a simple one Promise.
1. First, let's define Promisethe three states saved by the three static variables.

class MyPromise {
  // 定义promise3种状态 pending fulfilled rejected
  static Pending = "pending";
  static Fulfilled = "fulfilled";
  static Rejected = "rejected";
}

2. Next, define constructorthe constructor, which accepts a callback function

 constructor(callback) {
    this.promiseStatus = MyPromise.Pending; // 状态
    this.promiseResult = null; // 执行结果
    this.fulfilledCallbacks = [];  // 成功调用栈
    this.rejectedCallbacks = [];  // 失败调用栈
    try {
      callback(this.resolve.bind(this), this.reject.bind(this)); // 执行传入的函数
    } catch (err) {
      console.log(111, err);
      this.reject(err);
    }
  }

3. Implement the success callback function resolve.

// 实现resolve
  resolve(result) {
    setTimeout(() => {
      if (this.promiseStatus == "pending") {
        this.promiseStatus = "fulfilled";
        this.promiseResult = result;
        this.fulfilledCallbacks.forEach((callback) => { // 循环调用成功回调函数
          callback(result);
        });
      }
    });
  }

We setTimeoutuse simulate asynchrony. When the state pendingis , the success result is assigned to Promisethe execution result, and the success callback function is executed cyclically. After the execution is completed, Promisethe state pendingchanges from to fullfilled.
4. Implement the failure callback function reject.
This function receives Promisethe reason for the failure of the callback function as a parameter.

 // 实现reject
  reject(reason) {
    setTimeout(() => {
      if (this.promiseStatus == "pending") {
        this.promiseStatus = "rejected"; // 执行后将状态变更为rejected
        this.promiseResult = reason;  // 返回失败原因
        this.rejectedCallbacks.forEach((callback) => { // 循环执行失败回调
          callback(reason);
        });
      }
    });
  }

5. Implement then chain call
This function receives success callback and failure callback as parameters

  then(onFulfilled, onRejected) {
    onFulfilled =
      typeof onFulfilled == "function"
        ? onFulfilled
        : (value) => {
            return value;
          }; // 如果有传入的成功回调函数,直接使用,没有就把传入值作为返回值
    onRejected =
      typeof onRejected === "function"
        ? onRejected
        : (reason) => {
            return reason;
          }; // // 如果有传入的失败回调函数,直接使用,没有就把传入值作为返回值
    if (this.promiseStatus == "pending") { // 如果是pending状态 则将两个回调分别加入回调栈中
      this.fulfilledCallbacks.push(onFulfilled);
      this.rejectedCallbacks.push(onRejected);
    }
    if (this.promiseStatus == "fulfilled") { // 成功则加入成功回调栈
      setTimeout(() => {
        onFulfilled(this.promiseResult);
      });
    }
    if (this.promiseStatus == "rejected") { // 失败加入失败回调
      setTimeout(() => {
        onRejected(this.promiseResult);
      });
    }
  }

6. Code Verification

const promise = new MyPromise((resolve, reject) => {
  setTimeout(() => {
      resolve('success')
  }, 2000);
})
promise.then(value => {
  console.log(1)
  console.log('resolve', value)
})
promise.then(value => {
  console.log(2)
  console.log('resolve', value)
})
promise.then(value => {
  console.log(3)
  console.log('resolve', value)
})

print execution order

insert image description here

If it is resolve('success')changed to reject('fail'), only three are promised fail, catchewhich has not yet been realized.
The above is the simple version Promise的实现, if you like it, please like it.

Guess you like

Origin blog.csdn.net/Salange1/article/details/127581251