What is nextTick?

On vue’s official website, it is mentioned that nextTick is in an asynchronous update queue. Vue. Js usually encourages developers to think about code in a “data-driven” way and avoid direct contact with DOM. At this point we can update the graph through the vue.nexttick (callback) API. So we can interpret it as manually updating the view through the nextTick method. In addition, in the build we can use vm.nexttick () or this.nexttick () or this.nexttick () calls. NextTick () returns a Promise object, so we can use it in ES2017 with async/await syntax. Awaitthis.nexttick () returns a Promise object. So we can also use it in ES2017 with async/await syntax await this.nexttick () returns a Promise object, So we can also use it in ES2017 with async/await syntax awaitthis.nexttick ().

How is nextTick implemented?

NextTick returns a Promise object, which is a microtask. Let’s see how NextTick works! link

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 timerFunc() } // $flow-disable-line if (! cb && typeof Promise ! == 'undefined') { return new Promise(resolve => { _resolve = resolve }) } }Copy the code

In the code above we found the timerFunc method and you can see that timerFunc is the core of nextTick. In addition, there is a pending state in nextTick, which is supposed to control timerFunc execution. So what we’re going to do next is we’re going to look at the timerFunc function and the declaration of timerFunc appears at 33# but it has no value, okay

let timerFunc
Copy the code

Until #44 has an assignment, see it’s a method

# 44
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)
}
Copy the code

Also, #68, #77, and #82 all have timerFunc assignments

#68
timerFunc = () => {
  counter = (counter + 1) % 2
  textNode.data = String(counter)
}
#77
timerFunc = () => {
  setImmediate(flushCallbacks)
}
#82
timerFunc = () => {
  setTimeout(flushCallbacks, 0)
}
Copy the code

NextTick () nextTick () nextTick () nextTick () nextTick () nextTick () FlushCallbacks () is called when the other JS in the browser’s vue is finished to update the queue that needs to be flushed manually so that the flush can be attempted.