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) })