由于JavaScript是单线程语言 所以代码执行顺序是自上而下依次执行 但是遇到异步请求时 就不一样了 由此诞生宏任务和微任务
宏任务:script(整体代码)、setTimeout、setInterval...
微任务:promise.then/.catch await等待的值
任务的优先级:process.nextTick>promise.then>setTimeout
微任务是跟屁虫 一直跟在当前宏任务后面 代码执行到一个微任务就跟上 一个接着一个
练习一:
setTimeout(()=>{
console.log(1);
},0)
console.log(2);
new Promise((resolve,reject)=>{
console.log(3)
resolve()
}).then(()=>{
console.log(4);
}).then(()=>{
console.log(5);
})
console.log(6);
答案: 2 3 6 4 5 1
分析:2,3,6是立即执行的 不必多说 .then是异步 所以4 5是微任务 setTimeout是宏任务 所以要等4 5 执行完毕再执行
练习二:
setTimeout(() => {
new Promise(resolve => {
resolve();
}).then(() => {
console.log('test');
});
console.log(4);
});
new Promise(resolve => {
resolve();
console.log(1)
}).then(() => {
console.log(3);
Promise.resolve().then(() => {
console.log('before timeout');
}).then(() => {
Promise.resolve().then(() => {
console.log('also before timeout')
})
})
})
答案:1 3 before timeout also before timeout 4 test