I can’t remember where I first saw the call to process.nextTick. Oh, I should have seen it in the official nodejs process document. At that time, I didn’t understand what this thing was for. We already had setTimeout, so why did we need this function? And fundamentally speaking, what does this function do? What is the difference between setTimeout and setTimeout?
There is a very good post on stackoverflow that basically explains my problem. Here I attach the link and give an example in it:
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); }
To put it simply, because of the asynchronous model, some codes may be executed before the conditions they require are completed, so put these codes that require preconditions into a callback function, and then put Go to the top of the next event loop. Then these codes will not be executed immediately, but will wait before the next round of events is started, and will be executed after starting.