首页 > 解决方案 > 对 Promise 感到困惑,为什么打印“1 2 11 22”而不是“1 2 22 11”?

问题描述

我对Javascript中的Promise不是很擅长,今天看到一个让我困惑了一会儿的问题,代码如下:

new Promise((res, rej) => {
  res();
})
  .then(() => {
    console.log(1);
    new Promise((res, rej) => {
      res();
    })
      .then(() => {
        console.log(2);
      })
      .then(() => {
        console.log(22);
      });
  })
  .then(() => {
    console.log(11);
  });


我认为结果应该是 1 2 22 11,但我错了,真正的答案是1 2 11 22

为什么?请帮帮我,谢谢!

标签: javascriptpromise

解决方案


我们可以把它分成三部分:A、B、C

new Promise((res,rej)=>{
    // Part A
    res()
}).then(()=>{
    // Part B
    console.log(1)
    new Promise((res,rej)=>{
        // Part B-1
        res()
    }).then(()=>{
        // Part B-2
        console.log(2)
    }).then(()=>{
        // Part B-3
        console.log(22)
    })
}).then(()=>{
    // Part C
    console.log(11)
})

它从 print 1开始, 然后内部的 Promise 被解决(B-1 部分),两个任务被插入到任务队列中:

  1. B-2 部分console.log(2)
  2. C部分console.log(11)

然后执行第一个任务: print 2,完成后,在任务队列的末尾添加了另一个任务,新的任务队列如下所示:

  1. C部分console.log(11)
  2. B-3部分console.log(22) 然后按顺序执行任务:打印1122

所以结果是1 2 11 22

顺便说一句,如果我们想要1 2 22 11的顺序,我们可以在内部 promise 前面 添加关键字return :

new Promise((res,rej)=>{
    res()
}).then(()=>{
    console.log(1)
    return new Promise((res,rej)=>{
        res()
    }).then(()=>{
        console.log(2)
    }).then(()=>{
        console.log(22)
    })
}).then(()=>{
    console.log(11)
})

结果是1 2 22 11


推荐阅读