Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

异步编程: Promise 题目 2 - 3 - 2 #120

Open
leslie1943 opened this issue Jan 4, 2021 · 0 comments
Open

异步编程: Promise 题目 2 - 3 - 2 #120

leslie1943 opened this issue Jan 4, 2021 · 0 comments

Comments

@leslie1943
Copy link
Owner

Promise 题目 2 - 3 - 2

Promise.resolve().then(() => {
  console.log('promise1')
  const timer2 = setTimeout(() => {
    console.log('timer2')
  }, 0)
})

const timer1 = setTimeout(() => {
  console.log('timer1')
  Promise.resolve().then(() => {
    console.log('promise2')
  })
}, 0)

console.log('start')

// start, promise1, timer1,promise2,timer2

过程分析

  • promise 中执行定时器, 又在定时器中执行 promise
  • 并且要注意的是, 这里的 Promise 是直接 resolve 的, 而之前的 new Promise 不一样
  1. 刚开始整个脚本作为第一次宏任务来执行, 我们将它标记为 宏1, 从上至下执行
  2. 遇到 Promise.resolve().then 这个微任务, 将 then 中的内容加入第一次的微任务队列标记为 微1
  3. 遇到定时器 timer1, 将它加入下一次宏任务的延迟列表, 标记为宏2, 等待执行(先不管里面是什么内容)
  4. 执行宏1中的同步代码start
  5. 第一次宏任务(宏1)执行完毕, 检查第一次的微任务队列(微1), 发现有一个promise.then这个微任务需要执行
  6. 执行打印出微1中同步代码promise1, 然后发现定时器timer2, 将它加入宏2的后面, 标记为宏3
  7. 第一次微任务队列(微1)执行完毕, 执行第二次宏任务(宏2), 首先执行同步代码timer1
  8. 然后遇到了promise2这个微任务, 将它加入此次循环的微任务队列, 标记为微2
  9. 宏2中没有同步代码可执行了, 查找本次循环的微任务队列(微2), 发现了promise2, 执行它
  10. 第二轮执行完毕, 执行宏3, 打印出timer2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant