Skip to main content

宏任务与微任务

题目 1

    async function async1(){
console.log('async1 start'); //2
await async2();
console.log('async1 end'); //6
}

async function async2(){
console.log('async2'); //3
}

console.log('script start'); //1

setTimeout(function(){
console.log('setTimeout'); //8
},0)

async1();

new Promise(function(resolve){
console.log('promise1'); //4
resolve();
}).then(function(){
console.log('promise2'); //7
});

console.log('script end'); //5

请问打印的顺序是什么?

答案

script start
async1 start
async2
promise1
script end
async1 end
promise2
setTimeout

解答

通俗的来说就是主任务->微任务->宏任务

首先按照顺序执行,第一步是执行主任务,所以先执行console.log('script start');

第二步:来到async1();这行代码,开始执行函数 async1(),所以开始执行console.log('async1 start');

第三步:执行到await async2();的时候,实际上 await 是一个让出线程的标志,await 后面的代码先执行一遍,讲 await 后面的代码console.log('async1 end');放到下一轮主任务的队列中,所以就开始执行console.log('async2');

第四步:到达 promise,先执行里面的console.log('promise1');,将 then 后面的代码放到下一轮任务队列中

第五步:开始执行主任务的console.log('script end');,主任务执行完毕,然后开始下一轮的任务队列

第六步:开始执行 await 后面的任务console.log('async1 end');

第七步:顺序执行,遇到console.log('setTimeout');,但是 setTimeout 是宏任务,将这行代码放到下一轮的任务队列中,然后执行 then 后面的函数console.log('promise2');

第八步:全部任务执行完毕了,再去执行 setTimeout 的方法console.log('setTimeout');

题目 2

console.log(1)

setTimeout(() => {
console.log(2)
Promise.resolve().then(() => {
console.log(3)
})
})

new Promise((resolve, reject) => {
console.log(4)
resolve(5)
}).then(data => {
console.log(data)

Promise.resolve()
.then(() => {
console.log(6)
})
.then(() => {
console.log(7)

setTimeout(() => {
console.log(8)
}, 0)
})
})

setTimeout(() => {
console.log(9)
}, 0)

console.log(10)

答案

1 4 10 5 6 7 2 3 8 9