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

day-16-部分异步执行代码 #16

Open
H246802 opened this issue Dec 10, 2018 · 1 comment
Open

day-16-部分异步执行代码 #16

H246802 opened this issue Dec 10, 2018 · 1 comment

Comments

@H246802
Copy link
Owner

H246802 commented Dec 10, 2018

以下代码输出什么?为什么?

setTimeout(() => {
  console.log(4)
}, 0)
new Promise(resolve => {
  console.log(1)
  for (var i = 0; i < 10000; i++) {
    i == 9999 && resolve()
  }
  console.log(2)
}).then(() => {
  console.log(5)
  Promise.resolve(7)
  .then(v => console.log(v))
}).then(() => {
  console.log(6)
})
console.log(3)
@H246802
Copy link
Owner Author

H246802 commented Dec 10, 2018

setTimeout(() => {
  // a 
  console.log(4)
}, 0)
new Promise(resolve => {
  // b
  console.log(1)
  for (var i = 0; i < 10000; i++) {
    i == 9999 && resolve()
  }
  // c
  console.log(2)
}).then(() => {
  // d
  console.log(5)
  Promise.resolve(7)
  // e
  .then(v => console.log(v))
}).then(() => {
  // f
  console.log(6)
})
// g
console.log(3)

/*
a 
setTimeout 设定的计时器,函数会被添加到 event loop 中,
只有主线程的任务完成以后,才会执行,所以会最后打印 4
b 
js 解释器开始顺序执行代码,开始打印 1
c
当 for 循环中的循环变量自增到 9999,
会将 promise 对象的状态由 pending 变更为 fullfilled,
但 console.log(2) 仍要先于 resolved 的回调函数执行,
所以会打印 2,
g
resolve 状态下的回调函数会异步执行,
所以此时会执行 g 同步操作,打印 3
d
异步,resolved 状态下的回调函数开始执行,打印 5,
e
而此时,有一个新的 promsie 对象,
状态立即由 pending 变更为 fullfilled 的,
resolved 状态下的回调函数会立即执行,打印 7
f
第一个 then 的回调函数执行完毕后,
开始执行第二个 then 的回调函数,
即执行 f 操作,打印 6

所以,最后的顺序是
1,2,3,5,7,6,4
*/

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