Finding the node. JS documentation Today is a good explanation of how to use Process.nexttick.
node. js Document Link Http://nodejs.org/api/process.html#process_process_nexttick_callback
Process.nexttick (function callback () {});
node. JS ensures that callback is called before the next event is processed.
The following is a translation of the node. JS Document:
Process.nexttick (callback)
Call callback in the next event loop. This function is not simply equivalent to settimeout (FN, 0), it is more efficient. In general it is called before all other I/O events are triggered, but there are exceptions. Refer to the following process.maxTickDepth
.
Process.nexttick (function() { console.log (' Nexttick callback ');});
This function is important, especially when you are developing APIs that require the user to add an event handler to an object after it has been created, but before all other I/O.
function mything (options) { this. setupoptions (options); Process.nexttick (function() { this. Startdoingstuff (); }. Bind (this));} var New mything (); Thing.getreadyforstuff (); // Thing.startdoingstuff () gets called now, not before.
very important, the API should be 100% synchronous, or 100% async. Consider the following example:
// warning! Do not use! Bad UNSAFE hazard! function Maybesync (ARG, CB) { if (ARG) { CB (); return ; } Fs.stat (' file ', CB);}
This API is dangerous, if you call the API:
Maybesync (truefunction() { foo ();}); Bar ();
The ambiguous part of this code is that we don't know which Foo () and bar () will be called first.
It's better to write.
function Definitelyasync (ARG, CB) { if (ARG) { Process.nexttick (CB); return ; } Fs.stat (' file ', CB);}
node. JS uses Process.nexttick