process.nextTick(cb); Please use it

Idan Mor (sidanmor)
sidanmor
Published in
1 min readJul 18, 2017

--

It is very important for APIs to be either 100% synchronous or 100% asynchronous.

Consider this example:

This API is hazardous because in the following case:

It is not clear whether foo() or bar() will be called first.
The following approach is much better:

Note: The next tick queue is completely drained on each pass of the event loop before additional I/O is processed. As a result, recursively setting nextTick callbacks will block any I/O from happening, just like a while(true); loop.

If you want to use Promises, you can do it like this:

References:

https://nodejs.org/dist/latest-v8.x/docs/api/process.html

--

--

Full-Stack Team Leader, Senior Full-Stack Software Engineer and Javascript Ninja