/ walking bear:D / Node.js 的 process.nextTick() 用例

Node.js 的 process.nextTick() 用例

2017-05-10 posted in [筆記]

目前這套 nodeclub 使用了兩套 data store: mongodb + redis,覺得在搭配 node.js 應用,redis 是可有可無的部份,拿掉 redis 可以節約小電腦的運行資源。下手修改 common/cache.js,卻碰到一個技術坑:controllers/site.js在 rendering view 時,會整個卡住!經過一番掙扎,發現是 eventproxy 無法正常工作。原程式:

cache.get('tops', proxy.done(function (tops) {
....}); // 取排行榜上的用户
...
cache.get('no_reply_topics', proxy.done(function (no_reply_topics) {
..}); // 取0回复的主题
...
proxy.all('topics', 'tops', 'no_reply_topics', 'pages',
    function (topics, tops, no_reply_topics, pages) {
      res.render('index', {...
	  })});

所修改的 common/cache.js ,上層程式調用 cache.get(),即刻返回所需的 data,造成 eventproxy 罷工,修改使用 process.nextTick() 在下一個回調週期返回資料,整個 rendering view 就又活起來了!

function cache_get(key, callback) {
...
   // 不可以直接叫用 callback(null, data) 返回資料
	process.nextTick(function() {
		callback(null, data); 
	});
}

更清楚的技術說明,可參考這篇文章:Understanding process.nextTick() . reply_count: 2 get_replies : 2 . 2017-05-10_19:50:24 wkliang

Keeping callbacks truly asynchronous

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

上列的程式中,如果 net.connect() 沒有回到事件迴圈,而是直接調用 callback,則因變數 client 來不及被初始化,callback 已經開始叫用 client.write()。這種情況當然會出錯!

. 2017-05-10_22:08:24 wkliang

When emitting events

class 定義:

function StreamLibrary(resourceName) { 
    this.emit('start');
	// ...
}
StreamLibrary.prototype.__proto__ = require('events').EventEmitter.prototype;

應用:

var stream = new StreamLibrary('fooResource');
stream.on('start', function() {
    console.log('Reading has started');
});

上面的程式是有問題的,在 var strem = new StreamLibrary() 被執行時 constructor 就直接 emit('start'),其後的 stream.on('start',...) 都還來不及執行。必須修改成:

function StreamLibrary(resourceName) {      
    var self = this;
    process.nextTick(function() {
        self.emit('start');
    });
    //...
}

.

walking bear:DRSS feed

关于

wkliang

Clarke's Three Laws:

  • When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
  • The only way of discovering the limits of the possible is to venture a little way past them into the impossible.
  • Any sufficiently advanced technology is indistinguishable from magic.
  • 版权申明

    知识共享许可协议

    Fork me on GitHub

    Powered by

    Disqus, GitHub, Google Custom Search, Gravatar, HighlightJS, jekyll