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

作者: YanWen

Web 开发者

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s