event loop它的执行顺序:
1. 一开始整个脚本作为一个宏任务执行
2. 执行过程中同步代码直接执行,宏任务进入宏任务队列,微任务进入微任务队列
3. 当前宏任务执行完出队,检查微任务列表,有则依次执行,直到全部执行完
4. 执行浏览器UI线程的渲染工作
5. 检查是否有`Web Worker`任务,有则执行
6. 执行完本轮的宏任务,回到2,依此循环,直到宏任务和微任务队列都为空
微任务包括:
`MutationObserver`
`Promise.then()或catch()`
`Promise为基础开发的其它技术,
比如fetch API`、`V8`的垃圾回收过程
`Node独有的process.nextTick`
宏任务包括:
script、setTimeout、setInterval 、setImmediate 、I/O 、UI rendering
注意⚠️:在所有任务开始的时候,由于宏任务中包括了script,所以浏览器会先执行一个宏任务,在这个过程中你看到的延迟任务(例如setTimeout)将被放到下一轮宏任务中来执行。
//请写出输出内容
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');
/*
script start
async1 start
async2
promise1
script end
async1 end
promise2
setTimeout
*/
异步题2(改编)
async function async1() {
console.log('async1 start');
await async2();
console.log('async1 end');
}
async function async2() {
//async2做出如下更改:
new Promise(function(resolve) {
console.log('promise1');
resolve();
}).then(function() {
console.log('promise2');
});
}
console.log('script start');
setTimeout(function() {
console.log('setTimeout');
}, 0)
async1();
new Promise(function(resolve) {
console.log('promise3');
resolve();
}).then(function() {
console.log('promise4');
});
console.log('script end');
异步题3(改编)
async function async1() {
console.log("async1 start");
await async2();
//更改如下:
setTimeout(function() {
console.log("setTimeout1");
}, 0);
}
async function async2() {
//更改如下:
setTimeout(function() {
console.log("setTimeout2");
}, 0);
}
console.log("script start");
setTimeout(function() {
console.log("setTimeout3");
}, 0);
async1();
new Promise(function(resolve) {
console.log("promise1");
resolve();
}).then(function() {
console.log("promise2");
});
console.log("script end");
异步题4(改编)
asyncfunctiona1 () {
console.log('a1 start')
awaita2()
console.log('a1 end')
}
asyncfunctiona2 () {
console.log('a2')
}
console.log('script start')
setTimeout(() => {
console.log('setTimeout')
}, 0)
Promise.resolve().then(() => {
console.log('promise1')
})
a1()
let promise2 = newPromise((resolve) => {
resolve('promise2.then')
console.log('promise2')
})
promise2.then((res) => {
console.log(res)
Promise.resolve().then(() => {
console.log('promise3')
})
})
console.log('script end')