Node.js中的process.nextTick使用实例
我已经不记得是在哪里第一次看到process.nextTick这个玩意的调用了,哦,应该是在nodejs官方的process文档里看到的。当时就不理解这东西是干嘛的了,都已经有setTimeout了,还需要这个函数干嘛。而且从根本上来说,这个函数又是干嘛的?和setTimeout有什么区别?
stackoverflow上有一个非常好的帖子基本上解释了我的问题,这里我附上链接,然后给出它里面的范例:
stackoverflow.com >> What are the proper use cases for process.nextTick in Node.js?
var MyConstructor = function() {
...
process.nextTick(function() {
self._continue();
});
};
MyConstructor.prototype.__proto__ = EventEmitter.prototype;
MyConstructor.prototype._continue = function() {
// without the process.nextTick
// these events would be emitted immediately
// with no listeners. they would be lost.
this.emit('data', 'hello');
this.emit('data', 'world');
this.emit('end');
};
function(req, res, next) {
var c = new MyConstructor(...);
c.on('data', function(data) {
console.log(data);
});
c.on('end', next);
}
简单来说就是因为异步模型的关系,导致某些代码的执行可能先于它们所需要的条件完成之前,所以将这些需要先置条件的代码放入到一个回调函数中,然后放入到下一个事件循环的顶层。那么这些代码就不会被立刻执行了,而是在下一轮事件启动之前等待,启动后在进行执行。
把Node.js程序加入服务实现随机启动
如何开机就启动node.js程序npminstall-gqckwinsvc定位到安装目录,node_modules/.bin/运行如下命令:qckwinsvcprompt:Servicename:[nameforyourservice]prompt:Servicedescription:[descrip
使用Node.js配合Nginx实现高负载网络
在搭建高吞吐量web应用这个议题上,NginX和Node.js可谓是天生一对。他们都是基于事件驱动模型而设计,可以轻易突破Apache等传统web服务器的C10K瓶颈。预
nodejs实现获取当前url地址及url各种参数值
//需要使用的模块httpurl当前urlhttp://localhost:8888/selectaa=001&bb=002varhttp=require('http');varURL=require('url');http.createServer(function(req,res){vararg=url.parse(req.url).query;//方
编辑:广州明生医药有限公司
标签:是在,就不,函数,事件,代码