同步任务队列、宏观任务队列、微观任务队列

1、JS是单线程语言,包括同步任务、异步任务,异步任务又包括宏观任务和微观任务

2、执行顺序:同步任务——>微观任务——>宏观任务

3、宏观任务的方法有:script(整体代码)、setTimeout、setInterval、I/O、UI交互事件、postMessage、MessageChannel、setImmediate(Node.js 环境)

4、微观任务的方法有:Promise.then、MutaionObserver、process.nextTick(Node.js 环境),async/await实际上是promise+generator的语法糖,也就是promise,也就是微观任务

5、实例:

async function async1() {
  console.log('async1 start');
  await async2();
  console.log('async1 end');
}
async function async2() {
  console.log('async2');
}
 
console.log('script start');
 
setTimeout(function() {
  console.log('setTimeout');
}, 0)
 
async1();
 
new Promise(function(resolve) {
  console.log('promise1');
  resolve();
}).then(function() {
  console.log('promise2');
});
console.log('script end');

解析:
(1)从上到下,先走同步任务队列,再走异步任务队列
(2)同步任务:script start → async1 start → async2 → promise1 → script end
(3)微观任务:async1 end → promise2
(4)宏观任务:setTimeout


同步任务队列、宏观任务队列、微观任务队列_第1张图片
同步任务—微观任务—宏观任务.png

你可能感兴趣的:(同步任务队列、宏观任务队列、微观任务队列)