我已經(jīng)不記得是在哪里第一次看到process.nextTick這個(gè)玩意的調(diào)用了,哦,應(yīng)該是在nodejs官方的process文檔里看到的。當(dāng)時(shí)就不理解這東西是干嘛的了,都已經(jīng)有setTimeout了,還需要這個(gè)函數(shù)干嘛。而且從根本上來(lái)說(shuō),這個(gè)函數(shù)又是干嘛的?和setTimeout有什么區(qū)別?
stackoverflow上有一個(gè)非常好的帖子基本上解釋了我的問(wèn)題,這里我附上鏈接,然后給出它里面的范例:
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);}
簡(jiǎn)單來(lái)說(shuō)就是因?yàn)楫惒侥P偷年P(guān)系,導(dǎo)致某些代碼的執(zhí)行可能先于它們所需要的條件完成之前,所以將這些需要先置條件的代碼放入到一個(gè)回調(diào)函數(shù)中,然后放入到下一個(gè)事件循環(huán)的頂層。那么這些代碼就不會(huì)被立刻執(zhí)行了,而是在下一輪事件啟動(dòng)之前等待,啟動(dòng)后在進(jìn)行執(zhí)行。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注