Node.js中使用nextTick来调度工作

来源:互联网 发布:淘宝怎么入驻商家 编辑:程序博客网 时间:2024/06/10 18:10

在事件队列上调度工作的一个方法是process.nextTick(callback)函数,此函数调度要在事件循环的下一次循环中运行的工作。nextTick()在I/O在事件被触发之前执行,可能会导致I/O饥饿。所以Node.js通过默认值为1000的process.maxTickDepth来限制事件队列的每次循环可执行的nextTick()事件的数目。

var fs=require("fs");fs.stat("nexttick.js",function(err,stats){    if(stats)    {        console.log("nexttick.js Exists");    }    else{        console.log("not found");    }});setImmediate(function(){    console.log("immediate timer 1 executed");});setImmediate(function(){    console.log("immediate timer 2 executed");});process.nextTick(function(){    console.log("next tick 1 executed");});

上面这代码,从书上看到自己动手敲了一遍,书上的结果有问题。
正确结果为:
next tick 1 executed
next tick 2 executed
immediate timer 1 executed
immediate timer 2 executed
nexttick.js Exists

书也会错,所以看书还要长点心啊。

0 0
原创粉丝点击