1. 程式人生 > 實用技巧 >Redis實現延遲佇列方法介紹

Redis實現延遲佇列方法介紹

Vue你不得不知道的非同步更新機制和nextTick原理

前言#

非同步更新是Vue核心實現之一,在整體流程中充當著watcher更新的排程者這一角色。大部分watcher更新都會經過它的處理,在適當時機讓更新有序的執行。而nextTick作為非同步更新的核心,也是需要學習的重點。

本文你能學習到:

  • 非同步更新的作用
  • nextTick原理
  • 非同步更新流程

JS執行機制#

在理解非同步更新前,需要對JS執行機制有些瞭解,如果你已經知道這些知識,可以選擇跳過這部分內容。

JS 執行是單執行緒的,它是基於事件迴圈的。事件迴圈大致分為以下幾個步驟:

  1. 所有同步任務都在主執行緒上執行,形成一個執行棧(execution context stack)。
  2. 主執行緒之外,還存在一個"任務佇列"(task queue)。只要非同步任務有了執行結果,就在"任務佇列"之中放置一個事件。
  3. 一旦"執行棧"中的所有同步任務執行完畢,系統就會讀取"任務佇列",看看裡面有哪些事件。那些對應的非同步任務,於是結束等待狀態,進入執行棧,開始執行。
  4. 主執行緒不斷重複上面的第三步。

“任務佇列”中的任務(task)被分為兩類,分別是巨集任務(macro task)和微任務(micro task)

巨集任務:在一次新的事件迴圈的過程中,遇到巨集任務時,巨集任務將被加入任務佇列,但需要等到下一次事件迴圈才會執行。常見的巨集任務有 setTimeout、setImmediate、requestAnimationFrame

微任務:當前事件迴圈的任務佇列為空時,微任務佇列中的任務就會被依次執行。在執行過程中,如果遇到微任務,微任務被加入到當前事件迴圈的微任務佇列中。簡單來說,只要有微任務就會繼續執行,而不是放到下一個事件迴圈才執行。常見的微任務有 MutationObserver、Promise.then

總的來說,在事件迴圈中,微任務會先於巨集任務執行。而在微任務執行完後會進入瀏覽器更新渲染階段,所以在更新渲染前使用微任務會比巨集任務快一些。

關於事件迴圈和瀏覽器渲染可以看下 晨曦時夢見兮 大佬的文章《深入解析你不知道的 EventLoop 和瀏覽器渲染、幀動畫、空閒回撥(動圖演示)》

為什麼需要非同步更新#

既然非同步更新是核心之一,首先要知道它的作用是什麼,解決了什麼問題。

先來看一個很常見的場景:

Copy
created(){
    this.id = 10
    this.list = []
    this.info = {}
}

總所周知,Vue基於資料驅動檢視,資料更改會觸發setter函式,通知watcher進行更新。如果像上面的情況,是不是代表需要更新3次,而且在實際開發中的更新可不止那麼少。更新過程是需要經過繁雜的操作,例如模板編譯、dom diff,頻繁進行更新的效能當然很差。

Vue作為一個優秀的框架,當然不會那麼“直男”,來多少就照單全收。Vue內部實際是將watcher加入到一個queue陣列中,最後再觸發queue中所有watcherrun方法來更新。並且加入queue的過程中還會對watcher進行去重操作,因為在一個vue例項中data內定義的資料都是儲存同一個 “渲染watcher”,所以以上場景中資料即使更新了3次,最終也只會執行一次更新頁面的邏輯。

為了達到這種效果,Vue使用非同步更新,等待所有資料同步修改完成後,再去執行更新邏輯。

nextTick 原理#

非同步更新內部是最重要的就是nextTick方法,它負責將非同步任務加入佇列和執行非同步任務。Vue也將它暴露出來提供給使用者使用。在資料修改完成後,立即獲取相關DOM還沒那麼快更新,使用nextTick便可以解決這一問題。

認識 nextTick

官方文件對它的描述:

在下次 DOM 更新迴圈結束之後執行延遲迴調。在修改資料之後立即使用這個方法,獲取更新後的 DOM。

Copy
// 修改資料
vm.msg = 'Hello'
// DOM 還沒有更新
Vue.nextTick(function () {
  // DOM 更新了
})

// 作為一個 Promise 使用 (2.1.0 起新增,詳見接下來的提示)
Vue.nextTick()
  .then(function () {
    // DOM 更新了
  })

nextTick使用方法有回撥和Promise兩種,以上是通過建構函式呼叫的形式,更常見的是在例項呼叫this.$nextTick。它們都是同一個方法。

內部實現

Vue原始碼 2.5+ 後,nextTick的實現單獨有一個 JS 檔案來維護它,它的原始碼並不複雜,程式碼實現不過100行,稍微花點時間就能啃下來。原始碼位置在src/core/util/next-tick.js,接下來我們來看一下它的實現,先從入口函式開始:

Copy
export function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  // 1
  callbacks.push(() => {
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  // 2
  if (!pending) {
    pending = true
    timerFunc()
  }
  // $flow-disable-line
  // 3
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}
  1. cb即傳入的回撥,它被push進一個callbacks陣列,等待呼叫。
  2. pending的作用就是一個鎖,防止後續的nextTick重複執行timerFunctimerFunc內部建立會一個微任務或巨集任務,等待所有的nextTick同步執行完成後,再去執行callbacks內的回撥。
  3. 如果沒有傳入回撥,使用者可能使用的是Promise形式,返回一個Promise_resolve被呼叫時進入到then

繼續往下走看看timerFunc的實現:

Copy
// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
let timerFunc

// 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 next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  timerFunc = () => {
    p.then(flushCallbacks)
    // 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)
  }
  isUsingMicroTask = true
} else if (!isIE && 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, iOS7, Android 4.4
  // (#6466 MutationObserver is unreliable in IE11)
  let counter = 1
  const observer = new MutationObserver(flushCallbacks)
  const textNode = document.createTextNode(String(counter))
  observer.observe(textNode, {
    characterData: true
  })
  timerFunc = () => {
    counter = (counter + 1) % 2
    textNode.data = String(counter)
  }
  isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  // Fallback to setImmediate.
  // Technically it leverages the (macro) task queue,
  // but it is still a better choice than setTimeout.
  timerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else {
  // Fallback to setTimeout.
  timerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

上面的程式碼並不複雜,主要通過一些相容判斷來建立合適的timerFunc,最優先肯定是微任務,其次再到巨集任務。優先順序為promise.then>MutationObserver>setImmediate>setTimeout。(原始碼中的英文說明也很重要,它們能幫助我們理解設計的意義)

我們會發現無論哪種情況建立的timerFunc,最終都會執行一個flushCallbacks的函式。

Copy
const callbacks = []
let pending = false

function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

flushCallbacks裡做的事情 so easy,它負責執行callbacks裡的回撥。

好了,nextTick的原始碼就那麼多,現在已經知道它的實現,下面再結合非同步更新流程,讓我們對它更充分的理解吧。

非同步更新流程#

資料被改變時,觸發watcher.update

Copy
// 原始碼位置:src/core/observer/watcher.js
update () {
  /* istanbul ignore else */
  if (this.lazy) {
    this.dirty = true
  } else if (this.sync) {
    this.run()
  } else {
    queueWatcher(this) // this 為當前的例項 watcher
  }
}

呼叫queueWatcher,將watcher加入佇列

Copy
// 原始碼位置:src/core/observer/scheduler.js
const queue = []
let has = {}
let waiting = false
let flushing = false
let index = 0

export function queueWatcher (watcher: Watcher) {
  const id = watcher.id
  // 1
  if (has[id] == null) {
    has[id] = true
    // 2
    if (!flushing) {
      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 > index && queue[i].id > watcher.id) {
        i--
      }
      queue.splice(i + 1, 0, watcher)
    }
    // queue the flush
    // 3
    if (!waiting) {
      waiting = true
      nextTick(flushSchedulerQueue)
    }
  }
}
  1. 每個watcher都有自己的id,當has沒有記錄到對應的watcher,即第一次進入邏輯,否則是重複的watcher, 則不會進入。這一步就是實現watcher去重的點。
  2. watcher加入到佇列中,等待執行
  3. waiting的作用是防止nextTick重複執行

flushSchedulerQueue作為回撥傳入nextTick非同步執行。

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

  // keep copies of post queues before resetting state
  const activatedQueue = activatedChildren.slice()
  const updatedQueue = queue.slice()

  resetSchedulerState()

  // call component updated and activated hooks
  callActivatedHooks(activatedQueue)
  callUpdatedHooks(updatedQueue)
}

flushSchedulerQueue內將剛剛加入queuewatcher逐個run更新。resetSchedulerState重置狀態,等待下一輪的非同步更新。

Copy
function resetSchedulerState () {
  index = queue.length = activatedChildren.length = 0
  has = {}
  if (process.env.NODE_ENV !== 'production') {
    circular = {}
  }
  waiting = flushing = false
}

要注意此時flushSchedulerQueue還未執行,它只是作為回撥傳入而已。因為使用者可能也會呼叫nextTick方法。這種情況下,callbacks裡的內容為 ["flushSchedulerQueue", "使用者的nextTick回撥"],當所有同步任務執行完成,才開始執行callbacks裡面的回撥。

由此可見,最先執行的是頁面更新的邏輯,其次再到使用者的nextTick回撥執行。這也是為什麼我們能在nextTick中獲取到更新後DOM的原因。

總結#

非同步更新機制使用微任務或巨集任務,基於事件迴圈執行,在Vue中對效能起著至關重要的作用,它對重複冗餘的watcher進行過濾。而nextTick根據不同的環境,使用優先順序最高的非同步任務。這樣做的好處是等待所有的狀態同步更新完畢後,再一次性渲染頁面。使用者建立的nextTick執行頁面更新之後,因此能夠獲取更新後的DOM。