一个小demo理解js的任务队列

请写出下面代码的打印结果

console.log( 'script start' );

function run() {
  setTimeout(() => {
    console.log( 'timeout 1' );
  }, 0);

  new Promise((resolve, reject) => {
    console.log( 'promise 1' );
    resolve(1);
  }).then(() => {
    console.log( 'promise 1 then' );
  })

  setTimeout(() => {
    console.log( 'timeout 2' );
  }, 0);
}

run();

setTimeout(() => {
  console.log( 'timeout 3' );

  new Promise((resolve, reject) => {
    console.log( 'promise 2' );
    resolve(2);
  }).then(() => {
    console.log( 'promise 2 then' );
  })
}, 0);

console.log( 'script end' );

注意:一般情况下,js会先把同步代码执行完,然后再去执行异步代码

  1. 第一行 console.log 为同步代码,立即执行所以先打印script start
  2. 后面是一个函数声明,先跳过
  3. run() 函数执行
  4. 首先遇到一个定时器,不属于同步代码,所以会把他先放到宏任务队列中
此时的宏任务队列

console.log( 'timeout 1' );
  1. 遇到了一个 Promise,new Promise会立即执行的,属于同步代码,打印出promise 1,then里面的代码属于异步代码,但是它属于一个微任务,所以先放到微任务队列中
此时的微任务队列

console.log( 'promise 1 then' );
  1. 接着遇到了一个定时器,会把他放到宏任务队列中
此时的宏任务队列

console.log( 'timeout 1' );

console.log( 'timeout 2' );
  1. 继续执行 run() 后面的代码,遇到一个定时器,会把他继续放到宏任务队列中
此时的宏任务队列

console.log( 'timeout 1' );

console.log( 'timeout 2' );

console.log( 'timeout 3' );

new Promise((resolve, reject) => {
  console.log( 'promise 2' );
  resolve(2);
}).then(() => {
  console.log( 'promise 2 then' );
})
  1. 接着执行定时器后面的 console.log,同步代码,立即执行,打印出script end
  2. 此时这一整块代码的同步代码都执行完毕了,现在js会去查看微任务队列中有没有未执行完的代码,发现有,立即执行
此时的微任务队列

console.log( 'promise 1 then' );

打印promise 1 then,此时微任务队列已经全部执行完成了

  1. 接着该去查找宏任务队列了,
此时的宏任务队列

console.log( 'timeout 1' );

console.log( 'timeout 2' );

console.log( 'timeout 3' );

new Promise((resolve, reject) => {
  console.log( 'promise 2' );
  resolve(2);
}).then(() => {
  console.log( 'promise 2 then' );
})

发现宏任务队列中也有未执行完的代码,所以从上到下依次执行,前三个任务都属于同步代码,相信大家没什么疑问,连续打印出timeout 1timeout 2timeout 3

  1. 接着遇到了 Promise,前面已经说过了,Promise 内部代码属于同步代码,立即执行,打印出promise 2,then 里面的代码属于异步代码,放到微任务队列中
微任务队列

console.log( 'promise 2 then' );
  1. 此时,宏任务队列中的任务已经全部执行完毕,接着查看微任务队列,发现有未执行的代码,继续执行,打印promise 2 then
  2. 接着再查看宏任务队列是否还有未执行完成的任务,没有了,全部代码执行完成,停止

最终的打印结果为

script start
promise 1
script end
promise 1 then
timeout 1
timeout 2
timeout 3
promise 2
promise 2 then
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值