js事件循環(huán)
js處理異步主要有微任務(wù)(microTask)和 宏任務(wù) (macroTask),而從開始執(zhí)行一個宏任務(wù)–>執(zhí)行完這個宏任務(wù)中所有同步代碼—>清空當前微任務(wù)隊列中所有微任務(wù)—> UI渲染 。 這便是完成了一個事件循環(huán)(Tick), 然后開始執(zhí)行下一個宏任務(wù)(相當于下一輪循環(huán))。
簡單來說,Vue 在修改數(shù)據(jù)后,視圖不會立刻更新,而是等同一事件循環(huán)中的所有數(shù)據(jù)變化完成之后,再統(tǒng)一進行視圖更新。
Vue異步更新
<body>
<div id="app">
<p ref="dom">{{message}}</p> <button @click="changeValue">改變值</button>
</div>
</body>
<script>
new Vue( {
el: '#app',
data: {
message: 'hello world'
},
methods: {
changeValue() {
this.message = 'hello zhangShan'
console.log( this.$refs.dom.innerText )
}
}
} )
</script>
//輸出值為
//hello world
從上圖中,我們可以看出,我們改變了message后,立馬去輸出p標簽的text值,發(fā)現(xiàn)還是原來的值。這就很明顯了,vue的dom更新,并不是同步的。而是異步的,所以在輸出時,實際dom還并沒有更新。
那么,為什么要設(shè)計成異步的,其實很好理解,如果是同步的,當我們頻繁的去改變狀態(tài)值時,是不是會頻繁的導致我們的dom更新啊。這很顯然是不行的。
<body>
<div id="app">
<p ref="dom">{{message}}</p> <button @click="changeValue">改變值</button>
</div>
</body>
<script>
new Vue( {
el: '#app',
data: {
message: 'hello world'
},
methods: {
changeValue() {
this.message = 'hello zhangShan'
this.message = 'hello liShi'
this.message = 'hello wangWu'
this.message = 'hello chenLiu'
console.log( this.$refs.dom.innerText )
}
}
} )
</script>
像上圖這樣,如果vue同步更新的話,將會造成4次dom更新。故vue是異步dom更新的,且更新原理如下(借用官網(wǎng)的話):
Vue 在更新 DOM 時是異步執(zhí)行的。只要偵聽到數(shù)據(jù)變化,Vue 將開啟一個隊列,并緩沖在同一事件循環(huán)中發(fā)生的所有數(shù)據(jù)變更。如果同一個 watcher 被多次觸發(fā),只會被推入到隊列中一次。這種在緩沖時去除重復數(shù)據(jù)對于避免不必要的計算和 DOM 操作是非常重要的。然后,在下一個的事件循環(huán)“tick”中,Vue 刷新隊列并執(zhí)行實際 (已去重的) 工作。Vue 在內(nèi)部對異步隊列嘗試使用原生的 Promise.then、MutationObserver 和 setImmediate,如果執(zhí)行環(huán)境不支持,則會采用 setTimeout(fn, 0) 代替。
這句話大部分地方其實都很好理解,我也不做過多的說明,我只說明下這句話中(在下一個的事件循環(huán)"tick"中,vue刷新隊列并執(zhí)行實際工作),按理的理解,這個下一個事件循環(huán)"tick"其實是個泛指,他并不是指下一個事件循環(huán),才去刷新隊列。實際刷新隊列是有可能在本次事件循環(huán)的微任務(wù)中刷新的,也可能是在下一個事件循環(huán)中刷新的。這取決于代碼當前執(zhí)行的環(huán)境,如若當前執(zhí)行環(huán)境支持promise,那么nextTick內(nèi)部實際會用Promise去執(zhí)行,那么隊列刷新就會在本次事件循環(huán)的微任務(wù)中去執(zhí)行。
也就是說,如果當前環(huán)境支持promise,那么nextTick內(nèi)部會使用promise.then去執(zhí)行,否則,如果支持mutationObserver,那么會用mutationObserver(什么是mutationObserver),不過mutationObserver在vue2.5以后被棄用了。如果這兩種都不支持,才會使用setImmediate,MessageChannel(vue2.5以后才有),或者setTimeout(按順序,支持哪個優(yōu)先用哪個)。
這也就是vue的降級策略
優(yōu)先選擇微任務(wù)microtask(promise和mutationObserver),不支持的情況下,才不得不降級選用宏任務(wù)macrotask(setImmediate, MessageChannel, setTimeout)。
那么,為什么優(yōu)先選擇微任務(wù)呢
微任務(wù)執(zhí)行期在 本次宏任務(wù)執(zhí)行完之后,下個宏任務(wù)執(zhí)行之前,并且在UI渲染之前
所以在微任務(wù)中更新隊列是會比在宏任務(wù)中更新少一次UI渲染的。
下面我們來證實下我們的猜想,請看下面一段代碼
<body>
<div id="app">
<p ref="dom">{{message}}</p>
</div>
</body>
<script>
new Vue( {
el: '#app',
data: {
message: 'hello world'
},
mounted() {
//第一步
this.message = 'aaa'
// 第二步
setTimeout(() => { console.log('222') })
// 第三步
Promise.resolve().then((res) => { console.log('333') })
// 第四步
this.$nextTick(() => {
console.log('444'),
consol.log(this.$refs.dom)
})
// 第五步
Promise.resolve().then((res) => { console.log('555') }) } })
</script>
</script>

首先,從上圖中,我們可以看出
第四步優(yōu)先第二步輸出了 444 和 p標簽,從這里我們可以看出,chrome瀏覽器環(huán)境下 nextTick內(nèi)部是執(zhí)行了微任務(wù)的,所以優(yōu)先setTimeout輸出了。從這點上是可以驗證我們上面的說法的(至于其他環(huán)境下的,我這里就不測試了)
但是,我們還有個疑問,同樣是微任務(wù),為什么第三步的promise會晚于第四步輸出呢。按照我們js事件循環(huán)來看,第三步第四步都是微任務(wù)的話,第三步肯定會優(yōu)先第四步輸出的,但是我們看到的結(jié)果卻是第四步優(yōu)于第三步輸出了,這是為什么呢。其實這個跟我們改變數(shù)據(jù)觸發(fā)watcher更新的先后有關(guān),我們先看下面一段代碼驗證一下是不是跟數(shù)據(jù)改變觸發(fā)watcher更新的順序有關(guān),然后我們再來看為什么跟觸發(fā)watcher更新的順序有關(guān)。
<body>
<div id="app">
<p ref="dom">{{message}}</p>
</div>
</body>
<script>
new Vue( {
el: '#app',
data: {
message: 'hello world'
},
mounted() {
// 第二步
setTimeout(() => { console.log('222') })
// 第三步
Promise.resolve().then((res) => {
console.log('333')
})
// 第一步
this.message = 'aaa'
// 第四步
this.$nextTick(() => {
console.log('444')
console.log(this.$refs.dom) })
// 第五步
Promise.resolve().then((res) => {
console.log('555') }) }
})
</script>

大家發(fā)現(xiàn)沒有,這個時候,第三步的微任務(wù)是優(yōu)先執(zhí)行了的。是不是說明了,nextTick中的callback啥時候執(zhí)行,取決于數(shù)據(jù)是在什么時候發(fā)生了改變的啊。那么為什么會這樣呢。這我們就要從nextTick源碼來看看到底是怎么回事了。我們先來看看源碼
首先,我們知道(響應式原理請自行查看MVVM響應式原理或者vue源碼解析),當響應式數(shù)據(jù)發(fā)生變化時,是不是會觸發(fā)它的setter,從而通知Dep去調(diào)用相關(guān)的watch對象,從而觸發(fā)watch的update函數(shù)進行視圖更新。那我們先看看update函數(shù)做了啥
update() {
/* istanbul ignore else */
if ( this.lazy ) {
this.dirty = true
} else if ( this.sync ) {
/*同步則執(zhí)行run直接渲染視圖*/
this.run()
} else {
/*異步推送到觀察者隊列中,下一個tick時調(diào)用。*/
queueWatcher( this )
}
}
update中是不是調(diào)用了一個queueWatcher方法啊(我們先將update的調(diào)用稱作第一步,將queueWatcher函數(shù)的調(diào)用稱作第二步,后面用的上),我們再看這個方法做了什么
/*將一個觀察者對象push進觀察者隊列,在隊列中已經(jīng)存在相同的id則該觀察者對象將被跳過,除非它是在隊列被刷新時推送*/
export function queueWatcher( watcher: Watcher ) {
/*獲取watcher的id*/
const id = watcher.id
/*檢驗id是否存在,已經(jīng)存在則直接跳過,不存在則標記哈希表has,用于下次檢驗*/
if ( has[ id ] == null ) {
has[ id ] = true
if ( !flushing ) {
/*如果沒有flush掉,直接push到隊列中即可*/
queue.push( watcher )
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
let i = queue.length - 1
while (i >= 0 && queue[i].id > watcher.id) { i-- }
queue.splice(Math.max(i, index) + 1, 0, watcher) }
// queue the flush
if (!waiting) {
waiting = true
nextTick(flushSchedulerQueue)
}
}
}
可以看出,queueWatcher方法內(nèi)部主要做的就是將watcher push到了queue隊列當中。
同時當waiting為false時,調(diào)用了一次 nextTick方法, 同時傳入了一個參數(shù) flushSchedulerQueue,其實這個參數(shù),就是具體的隊列更新函數(shù),也就是說更新dom操作就是在這里面做的。
而這個waiting狀態(tài)的作用,很明顯是為了保證nextTick(flushSchedulerQueue)只會執(zhí)行一次。后續(xù)再通過this.xxx改變數(shù)據(jù),只會加入將相關(guān)的watcher加入到隊列中,而不會再次執(zhí)行nextTick(flushSchedulerQueue)。
現(xiàn)在我們將nextTick(flushSchedulerQueue) 稱作第三步
function flushSchedulerQueue () {
currentFlushTimestamp = getNow()
flushing = true
let watcher, id
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child.
//(because parent is always created before the child)
// 2. A component's user watchers are run before its render watcher
//(because user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort((a, b) => a.id - b.id)
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++)
{
watcher = queue[index]
if (watcher.before) {
watcher.before()
}
id = watcher.id
has[id] = null
watcher.run()
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production' && has[id] != null)
{ circular[id] = (circular[id] || 0) + 1
if (circular[id] > MAX_UPDATE_COUNT)
{ warn( 'You may have an infinite update loop '
+ ( watcher.user ? `in watcher with expression "${watcher.expression}"`
: `in a component render function.` ), watcher.vm )
break }
}
}
}
我們再來看看nextTick內(nèi)部,做了些啥
/**
1. Defer a task to execute it asynchronously.
*/
/* 延遲一個任務(wù)使其異步執(zhí)行,
在下一個tick時執(zhí)行,
一個立即執(zhí)行函數(shù),
返回一個function
這個函數(shù)的作用是在task或者microtask中推入一個timerFunc,
在當前調(diào)用棧執(zhí)行完以后以此執(zhí)行直到執(zhí)行到timerFunc
目的是延遲到當前調(diào)用棧執(zhí)行完以后執(zhí)行
*/
export const nextTick = (function () {
/*存放異步執(zhí)行的回調(diào)*/
const callbacks = []
/*一個標記位,如果已經(jīng)有timerFunc被推送到任務(wù)隊列中去則不需要重復推送*/
let pending = false
/*一個函數(shù)指針,
指向函數(shù)將被推送到任務(wù)隊列中,
等到主線程任務(wù)執(zhí)行完時,
任務(wù)隊列中的timerFunc被調(diào)用*/
let timerFunc
/*下一個tick時的回調(diào)*/
function nextTickHandler ()
{ /*一個標記位,標記等待狀態(tài)(
即函數(shù)已經(jīng)被推入任務(wù)隊列或者主線程,
已經(jīng)在等待當前棧執(zhí)行完畢去執(zhí)行),
這樣就不需要在push多個回調(diào)到callbacks
時將timerFunc多次推入任務(wù)隊列或者主線程*/
pending = false
/*執(zhí)行所有callback*/
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++)
{ copies[i]() }
}
// the nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore if
*/ /* 這里解釋一下,一共有Promise、MutationObserver以及setTimeout
三種嘗試得到timerFunc的方法 優(yōu)先使用Promise,
在Promise不存在的情況下使用MutationObserver,
這兩個方法都會在microtask中執(zhí)行,
會比setTimeout更早執(zhí)行,所以優(yōu)先使用。
如果上述兩種方法都不支持的環(huán)境則會使用setTimeout,
在task尾部推入這個函數(shù),等待調(diào)用執(zhí)行。
參考:https://www.zhihu.com/question/55364497
*/
if (typeof Promise !== 'undefined' && isNative(Promise))
{
/*使用Promise*/
var p = Promise.resolve()
var logError = err => { console.error(err) }
timerFunc = () => { p.then(nextTickHandler).catch(logError)
// in problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) setTimeout(noop) }
} else if (typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) ||
// PhantomJS and iOS 7.x MutationObserver.toString() === '[object MutationObserverConstructor]'
)) { // use MutationObserver where native Promise is not available,
// e.g. PhantomJS IE11, iOS7, Android 4.4
/*新建一個textNode的DOM對象,
用MutationObserver綁定該DOM并指定回調(diào)函數(shù),
在DOM變化的時候則會觸發(fā)回調(diào),
該回調(diào)會進入主線程(比任務(wù)隊列優(yōu)先執(zhí)行),
即textNode.data = String(counter)時便會觸發(fā)回調(diào)*/
var counter = 1
var observer = new MutationObserver(nextTickHandler)
var textNode = document.createTextNode(String(counter))
observer.observe(textNode, { characterData: true })
timerFunc = () => { counter = (counter + 1) % 2
textNode.data = String(counter) }
} else {
// fallback to setTimeout
/* istanbul ignore next
*/ /*使用setTimeout將回調(diào)推入任務(wù)隊列尾部*/
timerFunc = () => {
setTimeout(nextTickHandler, 0) }
} /* 推送到隊列中下一個tick時執(zhí)行 cb 回調(diào)函數(shù) ctx 上下文
*/
return function queueNextTick (cb?: Function, ctx?: Object)
{
let _resolve
/*cb存到callbacks中*/
callbacks.push(() => { if (cb)
{ try { cb.call(ctx) } catch (e) {
handleError(e, ctx, 'nextTick') } }
else if (_resolve) { _resolve(ctx) } })
if (!pending) {
pending = true
timerFunc() }
if (!cb && typeof Promise !== 'undefined')
{
return new Promise((resolve, reject) => {
_resolve = resolve })
}
}
})()
在這個函數(shù)內(nèi),我們可以看到
首先可以看出,nextTick是一個立即執(zhí)行函數(shù),也就是說這個函數(shù)在定義的時候就已經(jīng)自動執(zhí)行一次了,而自動執(zhí)行時,return function queueNextTick前面的代碼是不是就已經(jīng)執(zhí)行了啊。這也是nextTick第一次執(zhí)行
定義了一個函數(shù)timerFunc,這是個關(guān)鍵函數(shù),因為這個函數(shù)是怎樣的,決定了我們的nextTick內(nèi)部最終是執(zhí)行了微任務(wù),還是執(zhí)行了宏任務(wù)。(定義nextTick函數(shù)時就定義了)
定義了一個nextTickHandler函數(shù),這個函數(shù)作用很明顯,就是執(zhí)行我們調(diào)用nextTick時,所傳進來的callback回調(diào)函數(shù),也就是說當我們執(zhí)行
this.$nextTick(()=> {})
時,內(nèi)部傳遞進來的這個函數(shù),就是在nextTickHandler內(nèi)被執(zhí)行的。(定義nextTick函數(shù)時就定義了))
return了一個函數(shù)queueNextTick,所以我們可以看出,當我們平常調(diào)用this.$nextTick(cb)時以及上面調(diào)用nextTick(flushSchedulerQueue),實際上,是不是調(diào)用了這個queueNextTick啊, 此時,我們將queueNextTick稱為第四步。
這個時候,我們繼續(xù)看queueNextTick,這里做了什么啊
將傳入進來的callback回調(diào)函數(shù),push到了callbacks數(shù)組中,為后面nextTickHandler函數(shù)執(zhí)行callback做準備
當pending為false時,調(diào)用了timerFunc函數(shù),此時我們將timerFunc函數(shù)的執(zhí)行,稱為第五步
大家發(fā)現(xiàn)沒有,這個pending其實就是解開我們問題的關(guān)鍵啊,為什么這么說呢。我們先看timerFunc內(nèi)做了啥,再回過頭來解釋
那么timerFunc做啥了
if (
typeof Promise !== 'undefined' && isNative( Promise ) ) {
/*使用Promise*/
var p = Promise.resolve()
var logError = err => {
console.error( err )
}
timerFunc = () => {
p.then( nextTickHandler ).catch( logError )
// in problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS)
setTimeout(noop)
}
} else if (
typeof MutationObserver !== 'undefined' && (
isNative( MutationObserver ) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
) ) { // use MutationObserver where native Promise is not available,
// e.g. PhantomJS IE11, iOS7, Android 4.4
/*新建一個textNode的DOM對象,用MutationObserver綁定該DOM并指定回調(diào)函數(shù),在DOM變化的時候則會觸發(fā)回調(diào),
該回調(diào)會進入主線程(比任務(wù)隊列優(yōu)先執(zhí)行),
即textNode.data = String(counter)時便會觸發(fā)回調(diào)*/
var counter = 1
var observer = new MutationObserver(nextTickHandler)
var textNode = document.createTextNode(String(counter))
observer.observe(textNode, { characterData: true })
timerFunc = () => { counter = (counter + 1) % 2
textNode.data = String(counter) }
} else {
// fallback to setTimeout
/* istanbul ignore next */
/*使用setTimeout將回調(diào)推入任務(wù)隊列尾部*/
timerFunc = () => { setTimeout(nextTickHandler, 0) }
}
可以看出,timerFunc內(nèi)部定義了一些異步函數(shù),視當前執(zhí)行環(huán)境的不同,timerFunc內(nèi)部執(zhí)行的異步函數(shù)不同,他內(nèi)部可能是promise, 可能是mutationObserver, 可能是setTimeout。(我們當前例子是在chrome瀏覽器下,timerFunc內(nèi)部是Promise無疑)。但可以看出,不管內(nèi)部是什么異步函數(shù),它都在異步的回調(diào)中執(zhí)行了nextTickHandler,而nextTickHandler是決定我們調(diào)用
this.$nextTick(() => {})
時,內(nèi)部回調(diào)函數(shù)啥時候執(zhí)行的關(guān)鍵。
故可以得出結(jié)論,timerFunc內(nèi)部的異步函數(shù)的回調(diào)啥時候執(zhí)行,我們this.$nextTick()內(nèi)的回調(diào)就啥時候執(zhí)行
好,到了這一步,我們就可以來重新梳理下,代碼是怎么走的啦。
栗子1:
mounted() {
// 第一步
this.message = 'aaa'
// 第二步
setTimeout(() => { console.log('222') })
// 第三步
Promise.resolve().then((res) => { console.log('333') })
// 第四步
this.$nextTick(() => {
console.log('444')
console.log(this.$refs.dom) })
// 第五步
Promise.resolve().then((res) => { console.log('555') })
}
1.this.message = ‘a(chǎn)aa’ 執(zhí)行,響應式數(shù)據(jù)發(fā)生變化,是不是會觸發(fā)setter, 從而進一步觸發(fā)watcher的update方法,也就是我們前面說的第一步
2.update方法內(nèi)執(zhí)行了queueWatcher函數(shù)(也就是我們上面說的第二步),將相關(guān)watcher push到queue隊列中。并執(zhí)行了nextTick(flushSchedulerQueue) ,也就是我們上面說的第三步。此時,記住了,我們這里是第一次執(zhí)行了nextTick方法。此時,我們代碼中的
this.$nextTick()
還并沒有執(zhí)行,只執(zhí)行了this.message = ‘a(chǎn)aa’ , 但是vue內(nèi)部自動執(zhí)行了一次nextTick方法,并將flushSchedulerQueue當作參數(shù)傳入了
3.nexTick內(nèi)部代碼執(zhí)行,實際上是執(zhí)行了queueNextTick,傳入了一個flushSchedulerQueue函數(shù),將這個函數(shù)加入到了callbacks數(shù)組中,此時數(shù)組中只有一個cb函數(shù)flushSchedulerQueue。
4.pending狀態(tài)初始為false,故執(zhí)行了timerFunc,

5.timerFunc一旦執(zhí)行,發(fā)現(xiàn)內(nèi)部是一個promise異步回調(diào),是不是就加入到微任務(wù)隊列了,此時,是不是微任務(wù)隊列中的第一個任務(wù)啊。但注意,此時,callbacks內(nèi)的回調(diào)函數(shù)還并沒有執(zhí)行,是不是要等這個微任務(wù)執(zhí)行的時候,callbcaks內(nèi)的回調(diào)函數(shù)才會執(zhí)行啊
6.此時,跳出源碼,繼續(xù)向下執(zhí)行我們寫的代碼
栗子2:
···
mounted() {
// 第一步
this.message = 'aaa'
// 第二步
setTimeout(() => { console.log('222') })
// 第三步
Promise.resolve().then((res) => { console.log('333') })
// 第四步
this.refs.dom) })
// 第五步
Promise.resolve().then((res) => {
console.log('555') })
}
···
1.碰到setTimeout,加入宏任務(wù)隊列,
2.碰到第一個Promise(console.log(333)的這個), 加入微任務(wù)隊列,此時微任務(wù)隊列中,是不是就有兩個微任務(wù)啦。我們現(xiàn)在加入的這個是第二個
3.此時
this.$nextTick()
執(zhí)行,相當于就是調(diào)用了queueNextTick,并傳入了一個回調(diào)函數(shù)。此時注意了

之前,我們是不是執(zhí)行過一次queueNextTick啊,那么pending狀態(tài)是不是變?yōu)閠rue了,那么timerFunc是不是這個時候不會再執(zhí)行了,而此時唯一做的操作就是將傳入的回調(diào)函數(shù)加入到了callbacks數(shù)組當中。
所以,實際timerFunc這個函數(shù)的執(zhí)行,是在this.message = ‘a(chǎn)aa’ 執(zhí)行的時候調(diào)用的,也就意味著,timerFunc內(nèi)的異步回調(diào), 是在 this.message = ‘a(chǎn)aa’ 時被加入到了微任務(wù)隊列當中,而不是this.$nextTick()執(zhí)行時被加入到微任務(wù)隊列的。
所以這也就是前面我們?yōu)槭裁凑fpending狀態(tài)是解決問題的關(guān)鍵,因為他決定了,異步回調(diào)啥時候加入到微任務(wù)隊列
而
this.$nextTick(cb)
執(zhí)行時,唯一的作用就是將cb回調(diào)函數(shù)加入到了callbacks數(shù)組當中,那么在微任務(wù)隊列被執(zhí)行的時候,去調(diào)用callbacks中的回調(diào)函數(shù)時,是不是就會調(diào)用到我們現(xiàn)在加入的這個回調(diào)函數(shù)啊
4.繼續(xù),碰到第二個promise(console.log(555)的這個),又加入到微任務(wù)隊列中。
5.此時,微任務(wù)隊列中存在3個任務(wù),第一個是timerFunc中的promise回調(diào),第二個是console.log(333)的那個promise回調(diào),第三個是console.log(555)的那個promise回調(diào)。
6.故,同步代碼執(zhí)行完成后,優(yōu)先清空微任務(wù)隊列,那么是不是先執(zhí)行了第一個微任務(wù)啊,也就是timeFunc內(nèi)的那個微任務(wù)

而這個微任務(wù)一執(zhí)行,是不是調(diào)用了nextTickHandler, nextTickHandler是不是就依次執(zhí)行了callbacks中的回調(diào)函數(shù)啊,此時callbacks中有兩個回調(diào)函數(shù),第一個就是flushSchedulerQueue,用于更新dom,第二個就是我們傳進來的這個

所以,我們第二個回調(diào)函數(shù)執(zhí)行時,dom是不是已經(jīng)更新了啊。然后才輸出 444 和 p標簽
7.然后再取出第二個微任務(wù)去執(zhí)行,就輸出了333
8.再取出第三個微任務(wù)去執(zhí)行,就輸出了555
9.再之后,微任務(wù)隊列清空,開始下一輪循環(huán),取出宏任務(wù)隊列中的setTimeout的回調(diào)并執(zhí)行,輸出222。
這也就是所有的一個執(zhí)行過程了
總結(jié)
nextTick流程總結(jié):
1、將回調(diào)放到callbacks里等待執(zhí)行;
2、將執(zhí)行函數(shù)(flushCallbacks)放到微任務(wù)或宏任務(wù)里;原碼里按照是否原生支持Promise.then、MutationObserver和setImmediate的順序決策,都不支持則使用setTimeout
3、等到事件循環(huán)執(zhí)行到微任務(wù)或者宏任務(wù)時,執(zhí)行函數(shù)依次執(zhí)行callbacks里的回調(diào);