node. JS uses Process.nexttick

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.