前端異步代碼輸出題匯總
我看了一些帖子和面經(jīng),簡單的總結(jié)一下,比較常見和簡單的異步輸出題。要是侵權(quán)了,請(qǐng)聯(lián)系我刪帖。
const promise = new Promise((resolve, reject) => { console.log(1) console.log(2) }) promise.then(() => { console.log(3) }) console.log(4) 答案:1 2 4 解釋:順序執(zhí)行 打印 1,2 promise調(diào)用then方法,狀態(tài)是需要改變的,當(dāng)前沒有變,沒有不執(zhí)行。繼續(xù)打印4
const promise = new Promise((resolve, reject) => { console.log(1) setTimeout(() => { console.log('timerStart') resolve('success') console.log('timerEnd') }, 0) console.log(2) }) promise.then((res) => { console.log(res) }) console.log(4) 答案:1 2 4 timerStart timerEnd success 我的理解: 打印 1 遇到st定時(shí)器 進(jìn)入宏任務(wù)隊(duì)列 打印2 then 方法沒有被調(diào)用 (這里是進(jìn)入微任務(wù)隊(duì)列嗎,還是等狀態(tài)改變了再進(jìn)入微任務(wù)隊(duì)列???) 打印4 目前只有宏任務(wù) 去解決定時(shí)器里面的 打印 timerStart 將promise的狀態(tài)改變 此時(shí) then方法 進(jìn)入微任務(wù)隊(duì)列 打印timerEnd 宏任務(wù)結(jié)束 執(zhí)行微任務(wù) then方法,打印success
console.log('start') setTimeout(() => { console.log('a') Promise.resolve().then(() => { console.log('c') }) }) Promise.resolve().then(() => { console.log('b') setTimeout(() => { console.log('d') }) }) console.log('end') 答案:start end b a c d 我的理解: 打印start st宏任務(wù) then 微任務(wù) 打印 end 執(zhí)行微任務(wù) 因?yàn)橐呀?jīng)resolve了,所以可以調(diào)用then方法 打印b 遇到定時(shí)器2 宏任務(wù)隊(duì)列+1 微任務(wù)結(jié)束 宏任務(wù)隊(duì)列有兩個(gè),執(zhí)行第一個(gè) 打印a 又遇到了then 進(jìn)入微任務(wù) 這個(gè)宏任務(wù)已經(jīng)結(jié)束了 處理微任務(wù) 打印c 處理宏任務(wù)2 打印d
async function async1() { console.log("async1 start"); await async2(); console.log("async1 end"); setTimeout(() => { console.log('timer1') }, 0) } async function async2() { setTimeout(() => { console.log('timer2') }, 0) console.log("async2"); } async1(); setTimeout(() => { console.log('timer3') }, 0) console.log("start") 答案: async1 start async2 start async1 end timer2 timer3 timer1 我的理解: 調(diào)用async1函數(shù) 打印async1 start 遇到await了?。?! await 后面的這個(gè)函數(shù)我們還是要執(zhí)行的 調(diào)用async2函數(shù) st宏任務(wù)1 打印 async2 這個(gè)函數(shù)2已經(jīng)執(zhí)行完畢了 但是因?yàn)閍wait 所以函數(shù)1的代碼就不執(zhí)行了(放入微任務(wù)隊(duì)列中????????????) st宏任務(wù) 2 打印 start 微任務(wù) 繼續(xù)執(zhí)行async1函數(shù) 打印aysnc1 end st宏任務(wù)3 宏任務(wù)隊(duì)列 宏任務(wù)1 打印 tmier2 宏任務(wù)2打印timer3 宏任務(wù)3 打印timer1
今天時(shí)間有限,就先總結(jié)到這里。大家看看哪里有問題,可以提出來。
我也是第一次寫這種技術(shù),發(fā)現(xiàn)自己是個(gè)垃圾,寫的好爛,只有自己能看懂,還有一些地方說不清
祝大家面試順序~