setImmediate(callback[, ...args])
callback
<Function> 在本轮 Node.js 事件循环结束时调用的函数...args
<any> 调用callback
时要传入的可选参数。- 返回: <Immediate> 用于
clearImmediate()
在 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();
callback
<Function> The function to call at the end of this turn of the Node.js Event Loop...args
<any> Optional arguments to pass when thecallback
is called.- Returns: <Immediate> for use with
clearImmediate()
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();