JesseZhao1990 / blog

learing summary
MIT License
62 stars 7 forks source link

Vue源码中的nextTick的实现逻辑 #153

Open JesseZhao1990 opened 6 years ago

JesseZhao1990 commented 6 years ago

首先贴一下vue的源码,然后我们再一步步的分析

/* @flow */
/* globals MessageChannel */

import { noop } from 'shared/util'
import { handleError } from './error'
import { isIOS, isNative } from './env'

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

// Here we have async deferring wrappers using both microtasks and (macro) tasks.
// In < 2.4 we used microtasks everywhere, but there are some scenarios where
// microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690) or even between bubbling of the same
// event (#6566). However, using (macro) tasks everywhere also has subtle problems
// when state is changed right before repaint (e.g. #6813, out-in transitions).
// Here we use microtask by default, but expose a way to force (macro) task when
// needed (e.g. in event handlers attached by v-on).
let microTimerFunc
let macroTimerFunc
let useMacroTask = false

// Determine (macro) task defer implementation.
// Technically setImmediate should be the ideal choice, but it's only available
// in IE. The only polyfill that consistently queues the callback after all DOM
// events triggered in the same loop is by using MessageChannel.
/* istanbul ignore if */
if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  macroTimerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else if (typeof MessageChannel !== 'undefined' && (
  isNative(MessageChannel) ||
  // PhantomJS
  MessageChannel.toString() === '[object MessageChannelConstructor]'
)) {
  const channel = new MessageChannel()
  const port = channel.port2
  channel.port1.onmessage = flushCallbacks
  macroTimerFunc = () => {
    port.postMessage(1)
  }
} else {
  /* istanbul ignore next */
  macroTimerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

// Determine microtask defer implementation.
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  microTimerFunc = () => {
    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)
  }
} else {
  // fallback to macro
  microTimerFunc = macroTimerFunc
}

/**
 * Wrap a function so that if any code inside triggers state change,
 * the changes are queued using a (macro) task instead of a microtask.
 */
export function withMacroTask (fn: Function): Function {
  return fn._withTask || (fn._withTask = function () {
    useMacroTask = true
    const res = fn.apply(null, arguments)
    useMacroTask = false
    return res
  })
}

export function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  callbacks.push(() => {
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  if (!pending) {
    pending = true
    if (useMacroTask) {
      macroTimerFunc()
    } else {
      microTimerFunc()
    }
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

这么多代码,可能猛的一看,可能有点懵,不要紧,我们一步一步抽出枝干。首先我们看一下这个js文件里的nextTick的定义

export function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  callbacks.push(() => {
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  if (!pending) {
    pending = true
    if (useMacroTask) {
      macroTimerFunc()
    } else {
      microTimerFunc()
    }
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

我将代码精简一下。如下所示,下面的代码估计就比较容易看懂了。把cb函数放到会掉队列里去,如果支持macroTask,则利用macroTask在下一个事件循环中执行这些异步的任务,如果不支持macroTask,那就利用microTask在下一个事件循环中执行这些异步任务。

export function nextTick (cb?: Function, ctx?: Object) {
  callbacks.push(cb)
    if (useMacroTask) {
      macroTimerFunc()
    } else {
      microTimerFunc()
    }
}

这里再次普及一下js的event loop的相关知识,js中的两个任务队列 :macrotasks、microtasks

macrotasks: script(一个js文件),setTimeout, setInterval, setImmediate, I/O, UI rendering microtasks: process.nextTick, Promises, Object.observe, MutationObserver

执行过程: 1.js引擎从macrotask队列中取一个任务执行 2.然后将microtask队列中的所有任务依次执行完 3.再次从macrotask队列中取一个任务执行 4.然后再次将microtask队列中所有任务依次执行完 …… 循环往复

那么我们再看我们精简掉的代码都是干什么的呢?我们往异步队列里放回调函数的时候,我们并不是直接放回调函数,而是包装了一个函数,在这个函数里调用cb,并且用try catch包裹了一下。这是因为cb在运行时出错,我们不try catch这个错误的话,会导致整个程序崩溃掉。 我们还精简掉了如下代码

  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }

这段代码是干嘛的呢?也就是说我们用nextTick的时候,还可以有promise的写法。如果没有向nextTick中传入cb,并且浏览器支持Promise的话,我们的nextTick返回的将是一个Promise。所以,nextTick的写法也可以是如下这样的

 nextTick().then(()=>{console.log("XXXXX")})

vue源码里关于nextTick的封装的思路,也给我们一些非常有益的启示,就是我们平时在封装函数的时候,要想同时指出回调和promise的话,就可以借鉴vue中的思路。

大致的思路我们已经捋顺了。但是为什么执行macroTimerFunc或者microTimerFunc就会在下一个tick执行我们的回调队列呢?下面我们来分析一下这两个函数的定义。首先我们分析macroTimerFunc

let macroTimerFunc

if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  macroTimerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else if (typeof MessageChannel !== 'undefined' && (
  isNative(MessageChannel) ||
  // PhantomJS
  MessageChannel.toString() === '[object MessageChannelConstructor]'
)) {
  const channel = new MessageChannel()
  const port = channel.port2
  channel.port1.onmessage = flushCallbacks
  macroTimerFunc = () => {
    port.postMessage(1)
  }
} else {
  /* istanbul ignore next */
  macroTimerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

从上边的代码可以看出,如果浏览器支持setImmediate,我们就用setImmediate,如果浏览器支持MessageChannel,我们就用MessageChannel的异步特性,如果两者都不支持,我们就降价到setTimeout ,用setTimeout来把callbacks中的任务在下一个tick中执行

  macroTimerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }

分析完macroTimerFunc,下面我们开始分析microTimerFunc,我把vue源码中关于microTimerFunc的定义稍微精简一下

let microTimerFunc;
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  microTimerFunc = () => {
    p.then(flushCallbacks)
  }
} else {
  // fallback to macro
  microTimerFunc = macroTimerFunc
}

从上边精简之后的代码,我们可以看到microTimerFunc的实现思路。如果支持浏览器支持promise,就用promise实现。如果不支持,就降低到用macroTimerFunc

over,整体逻辑就是这样。。看着吓人,掰开了之后好好分析一下,还是挺简单的。