timers ---> poll ---> check ↑ 在poll阶段停留等待 | 𠃊_________________________𠃎
普通异步任务node
setTimeout(fn,1000)
`[{event:fn,time:1000ms}]` 2. JS就无论setTimeout这个任务了,继续去执行JS同步代码 3. 在poll阶段等待1000ms,时间到后到timers阶段执行fn
普通异步任务+setImmdiatechrome
setTimeout(fn1,1000) setImmidiate(fn2)
相信你注意到了上个板块中的“理想状况”四个字。
什么叫理想状况?那就是咱们假定eventloop的启动要比js的启动更快。数组
//test.js setTimeout(()=>{ console.log('fn1') },1000) setImmidiate(()=>{ console.log('fn2') }) $ node test.js //输出:fn1 fn2 $ node test.js //输出:fn2 fn1
因此说,eventloop和js代码,谁启动的更快就决定了执行的顺序!浏览器
const fn = ()=>{ setImmidiate(()=>{ console.log('a') setTimeout(()=>{ console.log('b') },0) }) setTimeout(()={ console.log('c') setImmidiate(()=>{ console.log('d') }) },0) } fn()
输出:a c b d异步
宏任务:一下子就作的异步任务async
微任务:立刻就作的异步任务ide
实例oop
setTimeout(() => console.log(4)) new Promise(resolve => { resolve() console.log(1) }).then(() => { console.log(3) }) console.log(2)
输出: 1 2 3(微任务) 4(宏任务)idea
async function fn1(){ console.log(1) await fn2() console.log(2) } async function fn2(){ console.log(3) } fn1() new Promise(function(resolve){ console.log(4) resolve() }).then(()=>{ console.log(5)} )
输出:1 3 4 2 5线程
tips:
await 展开
await fn2(); console.log(2) //能够合并为 fn2().then(()=>{ console.log(2) })