dpjayasekara
5/12/2018 - 11:29 AM

next_tick.js

exports.setup = setupNextTick;

function setupNextTick() {

  // ...redacted...
  
  // tickInfo is used so that the C++ code in src/node.cc can
  // have easy access to our nextTick state, and avoid unnecessary
  // calls into JS land.
  // runMicrotasks is used to run V8's micro task queue.
  const [
    tickInfo,
    runMicrotasks
  ] = process._setupNextTick(_tickCallback);

  // *Must* match Environment::TickInfo::Fields in src/env.h.
  const kHasScheduled = 0;
  const kHasPromiseRejections = 1;

  const queue = new FixedQueue();

  process.nextTick = nextTick;
  
  // Needs to be accessible from beyond this scope.
  process._tickCallback = _tickCallback;

  function _tickCallback() {
      // processes the nextTick queue
  }

  class TickObject {
    // ...redacted...
  }

  // `nextTick()` will not enqueue any callback when the process is about to
  // exit since the callback would not have a chance to be executed.
  function nextTick(callback) {
    if (typeof callback !== 'function')
      throw new ERR_INVALID_CALLBACK();

    if (process._exiting)
      return; 

    if (queue.isEmpty())
      tickInfo[kHasScheduled] = 1;
    queue.push(new TickObject(callback, args, getDefaultTriggerAsyncId()));
  }
}