Promise執(zhí)行輸入問題詳解

Promise.resolve().then(() => {
    console.log(0)
    return Promise.resolve(4)
  }).then(res => {
    console.log(res)
  })

  Promise.resolve().then(() => {
    console.log(1)
  }).then(() => {
    console.log(2)
  }).then(() => {
    console.log(3)
  }).then(() => {
    console.log(5)
  }).then(() => {
    console.log(6)
  }).then(() => {
    console.log(7)
  }).then(() => {
    console.log(8)
  })

  // 0 1 2 3 4 5 6 7 8
  // 宏任務(wù)
  // 執(zhí)行第一個宏任務(wù)promise.resolve,then里面的, () => {
  //   console.log(0)
  //   return Promise.resolve(4)
  // } 進入微任務(wù)隊列
  // 執(zhí)行第二個宏任務(wù)promise.resolve,then里面的, () => {
  //   console.log(1)
  // } 進入微任務(wù)隊列, 這時候宏任務(wù)執(zhí)行完了,微任務(wù)隊列有倆個任務(wù)

  // 微任務(wù)
  // () => {
  //   console.log(0)
  //   return Promise.resolve(4)
  // } 執(zhí)行,輸出0, 注冊一個job, 當(dāng)執(zhí)行棧為空的時候(也可以理解為本輪微任務(wù)隊列為空),job進入執(zhí)行隊列

  // () => {
  //   console.log(1)
  // } 執(zhí)行,輸出1,下一個then回調(diào)推入微任務(wù)隊列, 這個時候本輪執(zhí)行微任務(wù)隊列空了,job進入隊列

  // 所以執(zhí)行棧里面現(xiàn)在是
  // () => {
  //   console.log(2)
  // } 執(zhí)行,輸入2,下一個then回調(diào)推入微任務(wù)隊列

  // job 執(zhí)行,res => {
  //   console.log(res)
  // }推入微任務(wù)隊列

  // 所以執(zhí)行棧里面現(xiàn)在是
  // () => {
  //   console.log(3)
  // } 執(zhí)行,輸入3,下一個then回調(diào)推入微任務(wù)隊列

  // res => {
  //   console.log(res)
  // } 執(zhí)行, 輸入4

  // 之后就是then的;鏈式調(diào)用5 6 7 8
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容