我想知道是否有一些巧妙的方法来了解是否在当前节拍(声明函数的节拍)或Node.js事件的下一个节拍(或某个未来节拍)中调用了一个函数环
例如:
function foo(cb){
// we can fire callback synchronously
cb();
// or we can fire callback asynchronously
process.nextTick(cb);
}
说会像这样打电话给foo:
function outer(){
const currentTickId = process.currentTickId;
function bar(){ //bar gets created everytime outer is called..
if(process.currentTickId === currentTickId){
//do something
}
else{
// do something else
}
}
// foo is always called in the same tick that bar was
// declared, but bar might not be called until the next tick
foo(bar);
}
大多数应用程序都不需要这样的东西,但是我正在编写一个库,如果有可能的话,拥有这个功能会很有用!请注意process.currentTickId
由我为此示例构成
答案 0 :(得分:1)
看起来您已经发现了process.nextTick
。
您可以使用它来设置系统以实现“process.currentTickId
”,因为您问题中的代码表明您需要:
process.currentTickId = 0;
const onTick = () => {
process.currentTickId++;
process.nextTick(onTick);
};
process.nextTick(onTick);
答案 1 :(得分:0)
NPM 库: https://www.npmjs.com/package/event-loop-ticks
基于@Emmett 帖子的改进答案:
let _tick = 0;
const onTick = () => {
_tick++;
setImmediate(() => process.nextTick(onTick)).unref();
};
process.nextTick(onTick);