Understanding process.nextTick()

本文详细解释了Node.js中process.nextTick()的功能及其使用场景,包括如何通过它实现任务交错执行,保持回调函数的异步特性,以及在事件触发中的应用。

I have seen quite a few people being confused about process.nextTick(). Let's take a look at what process.nextTick() does, and when to use it.

As you might already know, every Node application runs on a single thread. What this means is that apart from I/O - at any time, only one task/event is processed by Node's event loop. You can imagine this event loop to be a queue of callbacks that are processed by Node on every tick of the event loop. So, even if you are running Node on a multi-core machine, you will not get any parallelism in terms of actual processing - all events will be processed only one at a time. This is why Node is a great fit for I/O bound tasks, and definitely not for CPU intensive tasks. For every I/O bound task, you can simply define a callback that will get added to the event queue. The callback will fire when the I/O operation is done, and in the mean time, the application can continue to process other I/O bound requests.

Given this model, what process.nextTick() actually does is defer the execution of an action till the next pass around the event loop. Let's take a simple example. If we had a function foo() which we wanted to invoke in the next tick, this is how we do it:

function foo() {
    console.error('foo');
}

process.nextTick(foo);
console.error('bar');

If you ran the above snippet, you will notice that bar will be printed in your console before foo, as we have delayed the invokation of foo() till the next tick of the event loop:

bar
foo

In fact, you can get the same result by using setTimeout() this way:

setTimeout(foo, 0);
console.log('bar');

However, process.nextTick() is not just a simple alias to setTimeout(fn, 0) - it's far more efficient.

More precisely, process.nextTick() defers the function until a completely new stack. You can call as many functions as you want in the current stack. The function that called nextTick has to return, as well as its parent, all the way up to the root of the stack. Then when the event loop is looking for a new event to execute, your nextTick'ed function will be there in the event queue and execute on a whole new stack.

Let's see where we can use process.nextTick():

Interleaving execution of a CPU intensive task with other events

Let's say we have a task compute() which needs to run almost continuously, and does some CPU intensive calculations. If we wanted to also handle other events, like serving HTTP requests in the same Node process, we can use process.nextTick() to interleave the execution of compute() with the processing of requests this way:

var http = require('http');

function compute() {
    // performs complicated calculations continuously
    // ...
    process.nextTick(compute);
}

http.createServer(function(req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World');
}).listen(5000, '127.0.0.1');

compute();

In this model, instead of calling compute() recursively, we use process.nextTick() to delay the execution of compute() till the next tick of the event loop. By doing so, we ensure that if any other HTTP requests are queued in the event loop, they will be processed before the next time compute() gets invoked. If we had not used process.nextTick() and had simply called compute() recursively, the program would not have been able to process any incoming HTTP requests. Try it for yourself!

So, alas, we don't really get any magical multi-core parallelism benefits by using process.nextTick(), but we can still use it to share CPU usage between different parts of our application.

Keeping callbacks truly asynchronous

When you are writing a function that takes a callback, you should always ensure that this callback is fired asynchronously. Let's look at an example which violates this convention:

function asyncFake(data, callback) {        
    if(data === 'foo') callback(true);
    else callback(false);
}

asyncFake('bar', function(result) {
    // this callback is actually called synchronously!
});

Why is this inconsistency bad? Let's consider this example taken from Node's documentation:

var client = net.connect(8124, function() { 
    console.log('client connected');
    client.write('world!\r\n');
});

In the above case, if for some reason, net.connect() were to become synchronous, the callback would be called immediately, and hence the client variable will not be initialized when the it's accessed by the callback to write to the client!

We can correct asyncFake() to be always asynchronous this way:

function asyncReal(data, callback) {
    process.nextTick(function() {
        callback(data === 'foo');       
    });
}

When emitting events

Let's say you are writing a library that reads from a source and emits events that contains the chunks that are read. Such a library might look like this:

var EventEmitter = require('events').EventEmitter;

function StreamLibrary(resourceName) { 
    this.emit('start');

    // read from the file, and for every chunk read, do:        
    this.emit('data', chunkRead);       
}
StreamLibrary.prototype.__proto__ = EventEmitter.prototype;   // inherit from EventEmitter

Let's say that somewhere else, someone is listening to these events:

var stream = new StreamLibrary('fooResource');

stream.on('start', function() {
    console.log('Reading has started');
});

stream.on('data', function(chunk) {
    console.log('Received: ' + chunk);
});

In the above example, the listener will never get the start event as that event would be emitted by StreamLibrary immediately during the constructor call. At that time, we have not yet assigned a callback to the start event yet. Therefore, we would never catch this event! Once again, we can use process.nextTick() to defer the emit till the listener has had the chance to listen for the event.

function StreamLibrary(resourceName) {      
    var self = this;

    process.nextTick(function() {
        self.emit('start');
    });

    // read from the file, and for every chunk read, do:        
    this.emit('data', chunkRead);       
}

I hope that demystifies process.nextTick(). If I have missed out something, please do share in the comments.


Process docs:http://nodejs.org/api/process.html

转载自:http://howtonode.org/understanding-process-next-tick

源码来自:https://pan.quark.cn/s/41b9d28f0d6d 在信息技术领域中,jQuery作为一个广受欢迎的JavaScript框架,显著简化了诸多操作,包括对HTML文档的遍历、事件的管理、动画的设计以及Ajax通信等。 本篇文档将深入阐释如何运用jQuery达成一个图片自动播放的功能,这种效果常用于网站的轮播展示或幻灯片演示,有助于优化用户与页面的互动,使网页呈现更加动态的视觉体验。 为了有效实施这一功能,首先需掌握jQuery的核心操作。 通过$符号作为接口,jQuery能够迅速选取DOM组件,例如$("#id")用于选取具有特定ID的元素,而$(".class")则能选取所有应用了某类class的元素。 在选定元素之后,可以执行多种行为,诸如事件监听、样式的变更、内容的更新以及动画的制作等。 关于“一个基于jQuery的图片自动播放功能”,首要任务是准备一组图片素材,这些素材将被整合至一个容器元素之中。 例如,可以构建一个div元素,将其宽度设定为单张图片的尺寸,再借助CSS实现溢出内容的隐藏,从而构建出水平滚动的初始框架。 ```html<div id="slider"> <img src="image1.jpg" alt="Image 1"> <img src="image2.jpg" alt="Image 2"> <!-- 更多图片内容... --></div>```接着,需要编写jQuery脚本以实现图片的自动切换。 这通常涉及到定时器的运用,以设定周期性间隔自动更换当前显示的图片。 通过使用`.fadeOut()`和`.fadeIn()`方法,能够实现图片间的平滑过渡,增强视觉效果。 ```javascript$(document).re...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值