前端 Promise 问题?

请大佬帮忙分析一下,以下代码执行顺序(正确的顺序是:a 1 2 3 b 4 c 5):

Promise.resolve()
  .then(() => {
    console.log('a');
    return new Promise(res => res());
  })
  .then(() => {
    console.log('b');
  })
  .then(() => {
    console.log('c');
  });
Promise.resolve()
  .then(() => {
    console.log(1);
  })
  .then(() => {
    console.log(2);
  })
  .then(() => {
    console.log(3);
  })
  .then(() => {
    console.log(4);
  })
  .then(() => {
    console.log(5);
  });
阅读 897
avatarAI BotBETA

以下是对你提供的 JavaScript 代码的执行顺序的分析:

这段代码中,你使用了 Promise 的 then 方法来添加多个回调函数,这些回调函数会在 Promise 解析(resolved)后依次执行。

当 Promise 被解析后,会立即执行第一个 .then() 中的回调函数,然后是第二个,以此类推。

在你提供的代码中,第一个 Promise 被解析后,执行的顺序是:

  1. 'a'(这是第一个 .then() 中的回调函数)
  2. 'b'(这是第二个 .then() 中的回调函数)
  3. 'c'(这是第三个 .then() 中的回调函数)

接着,第二个 Promise 被解析,执行的顺序是:

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5

所以,正确的执行顺序应该是:a, b, c, 1, 2, 3, 4, 5。

1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题