setImmediate(callback[, ...args])


在 I/O 事件的回调之后调度 callback 的“立即”执行。

当多次调用 setImmediate() 时,则 callback 函数会按照它们的创建顺序排队执行。 每次事件循环迭代都会处理整个回调队列。 如果立即定时器从正在执行的回调中排队,则直到下一次事件循环迭代才会触发该定时器。

如果 callback 不是函数,则将抛出 TypeError

此方法具有可使用 util.promisify() 获得的 promise 的自定义变体。

const util = require('util');
const setImmediatePromise = util.promisify(setImmediate);

setImmediatePromise('foobar').then((value) => {
  // value === 'foobar'(传入的值是可选的)
  // 这是在所有 I/O 回调之后执行的。
});

// 或者使用异步函数
async function timerExample() {
  console.log('Before I/O callbacks');
  await setImmediatePromise();
  console.log('After I/O callbacks');
}
timerExample();

Schedules the "immediate" execution of the callback after I/O events' callbacks.

When multiple calls to setImmediate() are made, the callback functions are queued for execution in the order in which they are created. The entire callback queue is processed every event loop iteration. If an immediate timer is queued from inside an executing callback, that timer will not be triggered until the next event loop iteration.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using util.promisify():

const util = require('util');
const setImmediatePromise = util.promisify(setImmediate);

setImmediatePromise('foobar').then((value) => {
  // value === 'foobar' (passing values is optional)
  // This is executed after all I/O callbacks.
});

// Or with async function
async function timerExample() {
  console.log('Before I/O callbacks');
  await setImmediatePromise();
  console.log('After I/O callbacks');
}
timerExample();