我已經不記得是在哪里第一次看到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);}
簡單來說就是因為異步模型的關系,導致某些代碼的執行可能先于它們所需要的條件完成之前,所以將這些需要先置條件的代碼放入到一個回調函數中,然后放入到下一個事件循環的頂層。那么這些代碼就不會被立刻執行了,而是在下一輪事件啟動之前等待,啟動后在進行執行。
新聞熱點
疑難解答