process.nextTick

nextTick 调用指明在下一个 event loop 中执行的逻辑。

场景 1,触发事件

const { EventEmitter } = require('events');

function complexOperations() {
  const events = new EventEmitter();

  process.nextTick(() => {
    events.emit('success');
  });

  return events;
}

complexOperations().on('success', () => {
  console.log('success!');
});

场景 2,Callback

Node’s documentation recommends that API s should always be 100% asynchronous
or synchronous. That means if you have a method that accepts a callback and may call
it asynchronously, then you should wrap the synchronous case in process.nextTick
so users can rely on the order of execution.

—— Node in Practice

const { EventEmitter } = require('events');
const fs = require('fs');

let content;

function readFileIfRequired(callback) {
  if (!content) {
    fs.readFile(__filename, 'utf8', (err, data) => {
      content = data;
      console.log('readFileIfRequired: readFile');
      callback(err, content);
    });
  } else {
    process.nextTick(() => {
      console.log('readFileIfReauired: cached');
      callback(null, content);
    });
  }
}

readFileIfRequired((err, data) => {
  console.log(`1. Length: ${data.length}`);

  readFileIfRequired((err, data2) => {
    console.log(`2. Length: ${data2.length}`);
  });

  console.log('x1b[32mReading file again...x1b[37m');
});

console.log('x1b[31mReading file...x1b[37m');

The callbacks that have been passed with process.nextTick are usually run at the
end of the current event loop. The number of callbacks that can be safely run is con-
trolled by process.maxTickDepth , which is 1000 by default to allow I/O operations to
continue to be handled.

—— Node in Practice

Scheduling nextTick on the event loop

参考:

  1. Alex Young, Marc Harter. Node in Practice. 2015

作者: V

Web Dev

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Google photo

您的留言將使用 Google 帳號。 登出 /  變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s