关于javascript:理解Promise

promise 标准原理及实现

三个状态

  • pending 筹备
  • fulfilled 胜利
  • rejected 失败

两个过程

(不可逆)

  • pending -> fulfilled
  • pending -> rejected

一个办法

  • then 其余的 都是 then 派生的办法

Promise 数据结构


{
  [[PromiseState]]: "fulfilled",  // 外部状态
  [[PromiseResult]]: 1 // 外部变量
}

Promise Demo 运行阐明

const p = new Promise(function (resolve, reject) {
  console.log(0);
  setTimeout(() => {
    const number = parseInt(Math.random() * 100);
    const isOdd = number % 2;
    if (isOdd) {
      resolve(number);
    } else {
      reject(0);
    }
  }, 2000);
});

console.log(1);

p.then((data) => {
  console.log(2);
}).catch((err) => {
  console.log(3);
});

console.log(4);
  • new Promise 属于同步执行
  • setTimeout 会开启异步线程
  • 程序 0 1 4 2
  • Promise 的参数是一个函数,该函数同步执行
  • Promise 的参数 函数的参数, resolve reject 也是函数

    • resolve 作用

      • promise 定义中调用,传入胜利后果
      • 扭转 PromiseState 的状态为 fulfilled
      • 设置 PromiseResult 值
    • reject 作用

      • promise 定义中调用,传入失败起因
      • 扭转 PromiseState 的状态为 rejected
      • 设置 PromiseResult 值
  • then 办法

    • 将监听函数退出队列
    • 返回一个新的 promise

promise 实质

生产者生产之模式,new promise 和 then 中生产回调提供生产,then catch finally; 达到链式调用形式改善回调天堂的目标

简略实现

const PROMISE_STATE_ENUM = {
  PEDDING: "pendding",
  FULFILLED: "fulfilled", // 胜利
  REJECTED: "rejected", // 失败
};

class MyPromise {
  callbacks = []; // 队列?数组?生产后出队?  还是应为 promise.All

  constructor(fn) {
    this.state = PROMISE_STATE_ENUM.PEDDING;
    this.result = void 0;
    // console.log("同步执行");

    fn(
      function resolve(data) {
        if (this.state === PROMISE_STATE_ENUM.PEDDING) {
          this.state = PROMISE_STATE_ENUM.FULFILLED;
          this.result = data;
          this.callbacks.map((fn) => {
            fn(this.result);
          });
        }
      }.bind(this),
      function reject() {
        this.state = PROMISE_STATE_ENUM.REJECTED;
        return this;
      }.bind(this)
    );
  }

  then(onFulfilled, onRejected) {
    const self = this;
    let promise2;

    if (this.state === PROMISE_STATE_ENUM.PEDDING) {
      promise2 = new MyPromise(function (resolve, reject) {
        self.callbacks.push(() => {
          // setTimeout(function () {
            let x = onFulfilled(self.result);
            resolve(x);
          // });
        });
      });
    }

    if (this.state === PROMISE_STATE_ENUM.FULFILLED) {
      console.log("getdata");
      onFulfilled(this.result);
    }

    if (this.state === PROMISE_STATE_ENUM.REJECTED) {
      onRejected(this.result);
    }

    return promise2;
  }

  catch(onRejected) {
    this.then(null, onRejected)
  }

  finally() {}

  static all() {}

  static race() {}
  static allSettled() {}
  static any() {}
  static resolve(a) {
    return a;
  }
  static reject() {}
}

const p = new MyPromise(function (resolve, reject) {
  setTimeout(() => {
    if (1) {
      resolve("should data 123");
    } else {
      reject("error");
    }
  }, 300);
});

// console.dir(MyPromise);
// console.log(p, "p");

const p1 = p.then(
  (resolve) => {
    // console.log(resolve, ": then 1");
    return 555
  },
  (error) => {
    console.log(error);
  }
);
// console.log(p1, "p1");

p1.then((data) => {
  // console.log(data, ": then 2");
});

// console.log(p, "p2");

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理