js为单线程,所以只能一行一行执行,但是js代码中不止存在同步函数,还存在异步函数的情况。
js中如何实现异步同步化?
js执行机制中分为宏任务和微任务,利用事件循环不停查找当执行栈内的宏任务执行结束,就会查找微任务中是否有需要执行的代码。如此不断循环。
异步函数在首次载入会划分到微任务中执行。
图片来源
macro-task(宏任务):包括整体代码script,setTimeout,setInterval
micro-task(微任务):Promise.then,process.nextTick
遇到promise立即执行
宏任务-微任务会导致什么样的代码差异?
当你设置一个定时器为3秒的时候,如果你的同步执行所花时间太长,时间就会超过3秒。因为需要先执行宏任务内的同步函数,然后再调用微任务中的异步函数,所以时间会超过3秒
如图所示
举个代码例子
console.log('1');
setTimeout(function() {
console.log('2');
process.nextTick(function() {
console.log('3');
})
new Promise(function(resolve) {
console.log('4');
resolve();
}).then(function() {
console.log('5')
})
})
process.nextTick(function() {
console.log('6');
})
new Promise(function(resolve) {
console.log('7');
resolve();
}).then(function() {
console.log('8')
})
setTimeout(function() {
console.log('9');
process.nextTick(function() {
console.log('10');
})
new Promise(function(resolve) {
console.log('11');
resolve();
}).then(function() {
console.log('12')
})
})
执行后的结果为
1直接执行=>setimout(宏任务2)=>process.nexttick(宏任务->微任务3)=>new promise(宏任务下立即执行4).then(宏任务->微任务5)=>process.nexttick(微任务6)=>new promise(立即执行7).then(微任务8)=>settimeout(宏任务9)=>process.nexttick(宏任务->微任务10)=>new promise(宏任务下立即执行11).then(宏任务->微任务12)
1 7 6 8 2 4 9 11 3 5 10 12