很浅的Promise

105 阅读1分钟

其实对于promise大家都是知道概念,却也有人产生疑问,它为什么是异步的,我们纠结的其实不是它为什么是异步的,而是并不知它是如何实现的,它为什么可以解决多任务同时执行的问题,所以我们应该带着什么样的疑问去研究promise?(受一位微信名为末班车的朋友启发)

今天我就给大家举出比较抽象又很有道理的几点:

抽象一例子:

  • 你为什么是个男人?这个答案就是为了繁衍下一代,这就是存在的意义

典型几例子:

  • 具体如何实现?

  • 应该去了解promise它具体是什么作用?

  • 它是干什么的?

  • 为什么用它就可以解决问题?

带着疑问研究,顺带帮忙梳理一下~

首先我们应该知道Promise是通过构造函数的方式来创建的new Promise( executor ),并且为 executor函数 传递参数:

function Promi(executor) {
  executor(resolve, reject);
  function resolve() {}
  function reject() {}
}

再来说一下Promise的三种状态: pending-等待, resolve-成功, reject-失败, 其中最开始为pending状态, 并且一旦成功或者失败, Promise的状态便不会再改变,所以根据这点:

function Promi(executor) {
  let _this = this;
  _this.$$status = 'pending';
  executor(resolve.bind(this), reject.bind(this));
  function resolve() {
    if (_this.$$status === 'pending') {
      _this.$$status = 'full'
    }
  }
  function reject() {
    if (_this.$$status === 'pending') {
      _this.$$status = 'fail'
    }
  }
}

其中$$status来记录Promise的状态,只有当promise的状态未pending时我们才会改变它的状态为'full'或者'fail', 因为我们在两个status函数中使用了this,显然使用的是Promise的一些属性,所以我们要绑定resolve与reject中的this为当前创建的Promise;
这样我们最最最基础的Promise就完成了~

不接受任何反驳,因为我只说了最基础的(偷笑😏)