欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Node.js中的process.nextTick使用實(shí)例

 更新時(shí)間:2015年06月25日 10:28:13   投稿:junjie  
這篇文章主要介紹了Node.js中的process.nextTick使用實(shí)例,nextTick函數(shù)有什么用、怎么用、和setTimeout有什么區(qū)別呢,本文就講解了這些知識,需要的朋友可以參考下

我已經(jīng)不記得是在哪里第一次看到process.nextTick這個(gè)玩意的調(diào)用了,哦,應(yīng)該是在nodejs官方的process文檔里看到的。當(dāng)時(shí)就不理解這東西是干嘛的了,都已經(jīng)有setTimeout了,還需要這個(gè)函數(shù)干嘛。而且從根本上來說,這個(gè)函數(shù)又是干嘛的?和setTimeout有什么區(qū)別?

stackoverflow上有一個(gè)非常好的帖子基本上解釋了我的問題,這里我附上鏈接,然后給出它里面的范例:

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);
}

 

簡單來說就是因?yàn)楫惒侥P偷年P(guān)系,導(dǎo)致某些代碼的執(zhí)行可能先于它們所需要的條件完成之前,所以將這些需要先置條件的代碼放入到一個(gè)回調(diào)函數(shù)中,然后放入到下一個(gè)事件循環(huán)的頂層。那么這些代碼就不會被立刻執(zhí)行了,而是在下一輪事件啟動之前等待,啟動后在進(jìn)行執(zhí)行。

相關(guān)文章

最新評論