Promise.then链式调用顺序

栏目: IT技术 · 发布时间: 4年前

内容简介:[TOC]想用Promise异步实现一个递归调用的接口,用来做简单AI的动作序列。发现一开始接触这个then的时候,不是很清楚,参考了网上的一些写法,改成自己的有问题,所以先静下心来研究一下这个调用的顺序问题先看个例子,参考[1]

[TOC]

想用Promise异步实现一个递归调用的接口,用来做简单AI的动作序列。发现一开始接触这个then的时候,不是很清楚,参考了网上的一些写法,改成自己的有问题,所以先静下心来研究一下这个调用的顺序问题

例子

先看个例子,参考[1]

new Promise((resolve, reject) => {
  console.log("promise")
  resolve()
 })
    .then(() => {	// 执行.then的时候生成一个promise是给最后一个.then的
        console.log("then1")
        new Promise((resolve, reject) => {
            console.log("then1promise")
            resolve()
        })
  .then(() => {// 执行这个.then的时候,生成的promise是下面一个then的
   console.log("then1then1")
  })
  .then(() => {
   console.log("then1then2")
  })
    })
    .then(() => {
  // 这个
        console.log("then2")
    })

结果:

promise
then1
then1promise
then1then1
then2
then1then2

问题:主要是疑惑then2在then1then1和then1then2之间

揭秘

理论

为了方便分析,列几个自己的理解,后面解释问题的时候方便。尤其是理论4和理论5

理论1:Promise是一个对象

Promise是一个对象,他包含了

  • 自己的函数体:new时候传进去的一个参数,是一个函数
  • 状态:fulfilled, pending, rejected
  • 异步函数队列:pending状态下放在这里的then回调函数体

理论2:resolve/reject是用来改变Promise对象的

  • resolve:pending改成fulfilled
  • reject:pending改成rejected

另外, resolve执行的时候会去检查Promise自己的队列,如果不是空的,会把回调函数体塞到nextTick队列中。 代码参考[4]

handlers.resolve = function (self, value) {
  var result = tryCatch(getThen, value);
  if (result.status === 'error') {
    return handlers.reject(self, result.value);
  }
  var thenable = result.value;

  if (thenable) {
    safelyResolveThenable(self, thenable);
  } else {
    self.state = FULFILLED;
    self.outcome = value;
    var i = -1;
    var len = self.queue.length;
    while (++i < len) {
      self.queue[i].callFulfilled(value);
    }
  }
  return self;
};

理论3:Promise的t’hen/catch方法执行后返回的也是一个Promise对象

参考[2],返回的Promise对象支持了链式调用

理论4:then函数返回的Promise对象什么时候resolve看返回值

参考[2]返回值一节

(1)返回了一个值,那么 then 返回的 Promise 将会成为接受状态,并且将返回的值作为接受状态的回调函数的参数值。
(2)没有返回任何值,那么 then 返回的 Promise 将会成为接受状态,并且该接受状态的回调函数的参数值为 undefined。
(3)抛出一个错误,那么 then 返回的 Promise 将会成为拒绝状态,并且将抛出的错误作为拒绝状态的回调函数的参数值。
(4)返回一个已经是接受状态的 Promise,那么 then 返回的 Promise 也会成为接受状态,并且将那个 Promise 的接受状态的回调函数的参数值作为该被返回的Promise的接受状态回调函数的参数值。
(5)返回一个已经是拒绝状态的 Promise,那么 then 返回的 Promise 也会成为拒绝状态,并且将那个 Promise 的拒绝状态的回调函数的参数值作为该被返回的Promise的拒绝状态回调函数的参数值。
(6)返回一个未定状态(pending)的 Promise,那么 then 返回 Promise 的状态也是未定的,并且它的终态与那个 Promise 的终态相同;同时,它变为终态时调用的回调函数参数与那个 Promise 变为终态时的回调函数的参数是相同的。

理论5:执行顺序为:同步执行 > nextTick队列 > setTimeout队列 > Promise对象私有队列

参考[3],文章写的不错。大体讲明白了Promise和then的原理了。因为文章里面的截图不是很清楚,我还是去github上面翻源码出来看的舒服点,参考[4]

Promise.prototype.then = function (onFulfilled, onRejected) {
  if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
    typeof onRejected !== 'function' && this.state === REJECTED) {
    return this;
  }
  var promise = new this.constructor(INTERNAL);
  if (this.state !== PENDING) {
    var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
    unwrap(promise, resolver, this.outcome);
  } else {
    this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  }

  return promise;
};

简单说明:

    1. 执行then函数的时候,如果Promise状态是Fulfilled的话,就执行unwrap那个逻辑,把then函数体通过nextTick放到一个全局的队列
    1. 执行then函数的时候,如果Promise是Pending状态,就执行 this.queue.push ,看到this就知道这个是放在Promise对象自己的一个队列里面

分析时序

有了上面的这些理解,接下来分析一下一开始我不理解的打印结果。有些步骤简单明了,可能被我过了。当然,因为自己第一次去接触这个,所以步骤会写的比较繁琐一点~

  • 1.执行Promise的时候,函数体同步执行,直接resolve,所以Promise对象为fulfilled状态。[理论1,理论2]
  • 2.同步执行then1函数的时候,then本身是一个函数,只是它的参数(里面的函数体)没有执行。这个函数体放在nextTick队列中[理论5]。then1执行完的时候,同步返回一个匿名的Promise对象[理论3]。并且这个Promise对象的状态是Pending,因为这个对象相关的then1函数体还没有执行[理论4]
  • 3.同步执行then2。同上,它依赖then1返回的匿名Promise对象状态。因为是pending,那么then2函数体放在then1返回的匿名Promise对象自己的队列中
  • 4.下一个循环执行nextTick队列,也就是then1的函数体
  • 5.先同步执行一个new的Promise对象函数体,打印’then1 promise’.并且这个Promise对象的状态被resolve切换为fulfilled
  • 6.同步执行then1then1这个.then函数,并且把她的参数(回调函数体)放在nextTick队列中。并且返回的匿名Promise对象为pending状态
  • 7.同步执行then1then2这个.then函数,因为上面一个then1then1回调函数体还没有执行,返回一个pending状态的匿名Promise对象.所以这个then1then2函数回调函数体放在上面的匿名Promise对象的队列中
  • 8.最后,then1函数体没有返回任何东西,所以根据[理论4],这个Promise的状态变成了fulfilled,即第一个.then1函数返回的Promise对象的状态改变了。这个时候其实是执行了resolve函数切换状态,这个函数里面会看这个Promise对象自己的队列里面是不是有回调函数,然后把这些放到timeTick队列里面[理论3]。所以.then2的回调函数体从Promise对象自己的队列移到了nextTick队列里面。注意这个时候then1then1和then2的函数体都在tick队列中,但是都没有执行。再加上js是单线程,会顺序执行tick队列里面的回调函数体,所以接下来就按顺序执行then1then1和then2
  • 9.再下一个循环,分别执行then1then1和then2两回调函数体,所以会先打印‘then1then1’,然后是’then2’
  • 10.then1then1回调函数体执行完毕的时候,她的Promise对象也会切换为fulfilled,并且把then1then2回调函数体放在tick队列中
  • 11.再再下一个循环。最后执行then1then2函数体,打印’then1then2’。完美收官

练习

如果例子中的new Promise改成,前面加一个return呢?

.then(() => {	// 执行.then的时候生成一个promise是给最后一个.then的
        console.log("then1")
        new Promise((resolve, reject) => {
            console.log("then1promise")
            resolve()
        })

// ===》改成
.then(() => {	// 执行.then的时候生成一个promise是给最后一个.then的
        console.log("then1")
        // 就是这里的加了一个return
        return new Promise((resolve, reject) => {
            console.log("then1promise")
            resolve()
        })

根据[理论4],.then1函数体有了返回值,是一个Promise对象,而且是then1then2执行完返回的匿名Promise对象。所以只有等这个Promise对象resolve了之后,才会执行then2回调函数体的逻辑,所以’then2’最后才会打印。所以最终结果是:

promise
then1
then1promise
then1then1
then1then2
then2

参考

[1] 嵌套的promise执行顺序

[2] Promise.then

[3] 从一道Promise执行顺序的题目看Promise实现

[4] lie

[5] Promise

[6] Promise 链式调用顺序引发的思考


以上所述就是小编给大家介绍的《Promise.then链式调用顺序》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Clean Code

Clean Code

Robert C. Martin / Prentice Hall / 2008-8-11 / USD 49.99

Even bad code can function. But if code isn’t clean, it can bring a development organization to its knees. Every year, countless hours and significant resources are lost because of poorly written code......一起来看看 《Clean Code》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码