Promise 的执行顺序问题

遇到这样一个问题,打印结果是 0 1 2 3 4 5 6,我的理解是then中返回Promise会隐式调用一次 Promise的then在其中进行父级then的resolve,但是似乎这里调用了两次then。

Promise.resolve()
    .then(() => {
        console.log('0');
        return new Promise(resolve => {
            return resolve(4);
        });
    })
    .then(res => {
        console.log(res);
    });
Promise.resolve()
    .then(() => {
        console.log('1');
    })
    .then(() => {
        console.log('2');
    })
    .then(() => {
        console.log('3');
    })
    .then(() => {
        console.log('5');
    })
    .then(() => {
        console.log('6');
    });

给返回的Promise添加一个then,执行结果依然是 0 1 2 3 4 5 6

Promise.resolve()
    .then(() => {
        console.log('0');
        return new Promise(resolve => {
            return resolve(4);
        }).then(() => 4);
    })
    .then(res => {
        console.log(res);
    });
Promise.resolve()
    .then(() => {
        console.log('1');
    })
    .then(() => {
        console.log('2');
    })
    .then(() => {
        console.log('3');
    })
    .then(() => {
        console.log('5');
    })
    .then(() => {
        console.log('6');
    });

哪位大佬解答一下

阅读 3.6k
2 个回答
Promise.resolve()
  .then(() => {// promise0
    console.log('0');
    return new Promise(resolve => {// promise1
      resolve(4);
    });
  })
  .then(res => {// promise2
    console.log(res);
  });

Promise.resolve()
  .then(() => {// promise3
    console.log('1');
  })
  .then(() => {// promise4
    console.log('2');
  })
  .then(() => {// promise5
    console.log('3');
  })
  .then(() => {// promise6
    console.log('5');
  })
  .then(() => {// promise7
    console.log('6');
  });

用注释标注了下会产生promise的地方,对照下面描述查看,大概顺序是这样:

  1. promise0执行,log(0),promise1放入微任务队列等待执行
  2. promise3执行,log(1),promise4放入微任务队列等待执行
  3. promise1完成,promise0放入微任务队列等待执行
  4. promise4执行,log(2),promise5放入微任务队列等待执行
  5. promise0完成,promise2将放入微任务队列等待执行
  6. promise5执行,log(3),promise6放入微任务队列等待执行
  7. promise2执行,log(4)
  8. promise6执行,log(5),promise7放入微任务队列等待执行
  9. promise7执行,log(6)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题