Event Loop

文章promise

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
  • stime1 放入宏任務隊列任務
  • process.nextTick ,process1進入微任務隊列,
  • new promise 當即執行 //7
  • then1放入微任務隊列
  • stime2 放入入宏任務隊列
  • 完成第一個宏任務(總體代碼script)
  • 執行微任務process1 then1 //6 8
  • 結束第一次循環,開始第二次循環,執行宏任務stime1,//2
  • process2放入微隊列中
  • new promise //4
  • 添加微任務then2
  • 執行微任務process2 then2 結束第二次循環 // 3 5
  • 執行宏任務stime2 // 9
  • 新增微任務process3
  • new promise //11
  • 添加微任務then3
  • 執行process3 then3 結束第三次循環 // 10 12
    因此輸出結果1 7 6 8 2 4 3 5 9 11 10 12
相關文章
相關標籤/搜索