setTimeout(function() {
console.log('setTimeout');
})
new Promise(function(resolve) {
console.log('promise');
}).then(function() {
console.log('then');
})
console.log('console');
复制代码
setTimeout
,将其回调函数注册后分发到宏任务事件队列中(做为下一次循环宏任务调用)Promise
,new Promise
当即执行,打印'promise',then
函数分发到微任务事件队列(本次宏任务的微任务)console.log()
,当即执行then
,执行setTimeout
,打印'promise'console.log('Hello World!');
const p1 = new Promise((resolve) => {
console.log(3);
resolve(4);
});
const p2 = new Promise((resolve) => {
console.log(1);
setTimeout(() => {
console.log(6)
}, 0);
resolve(2);
});
p1.then((res) => {
console.log(res)
});
p2.then((res) => {
console.log(res)
});
console.log(5);
复制代码
p1
中打印'3',resolve(4)
在then
函数中分发到微任务事件队列p2
中打印'1',遇到setTimeout
,将其回调函数注册分发到宏任务事件队列resolve(2)
在then
函数中分发到微任务事件队列;向下执行,再打印'5'setTimeout
,打印'6'console.log('1');
setTimeout(function first () {
console.log('2');
setTimeout(function third () {
new Promise(function(resolve) {
console.log('3');
resolve();
}).then(function() {
console.log('4')
})
})
})
new Promise(function(resolve) {
console.log('5');
resolve();
}).then(function() {
console.log('6')
})
setTimeout(function second () {
console.log('7');
new Promise(function(resolve) {
console.log('8');
resolve();
}).then(function() {
console.log('9')
})
})
复制代码
setTimeout
的回调函数first
注册分发到宏任务事件队列Promise
中打印'5',then
函数分发到微任务事件队列setTimeout
,将其回调函数second
注册分发到宏任务事件队列中then
函数,打印'6'first
函数打印'2';而后又遇到了setTimeout
函数,将third
函数注册分发到宏任务事件队列中(下次循环才会调用)second
函数打印'7',进入promise
打印'8',then
函数注册分发到微任务事件队列then
函数,打印'9'third
函数,先打印'3',再执行then
中打印'4'全部的同步任务都在主线程上执行,造成一个执行栈javascript
主线程以外,还存在一个任务队列,只要异步任务有了运行结果,就在任务队列中放置一个事件java
一旦执行栈中全部同步任务执行完毕,系统就会读取任务队列中的事件,异步任务结束等待状态,进入执行栈,开始执行node
重复上一步(事件轮循——重复读取主线程和任务队列中的事件)promise
在js中的任务作更精确的定义:异步
在本次循环执行中,先执行宏任务,再执行微任务,都完成后,开始第二轮循环,执行宏任务,执行微任务,直到没有宏任务,完成执行函数
图片来源post