Understanding process.nextTick()

As you try to understand the Node.js event loop, one important part of it is process.nextTick(). Every time the runtime calls back into JavaScript for an event, we call it a tick.

When we pass a function to process.nextTick(), we instruct the engine to invoke this function immediately after the current operation completes, before moving to the next phase in the event loop:

var process: NodeJS.Processprocess.NodeJS.Process.nextTick(callback: Function, ...args: any[]): void
`process.nextTick()` adds `callback` to the "next tick queue". This queue is fully drained after the current operation on the JavaScript stack runs to completion and before the event loop is allowed to continue. It's possible to create an infinite loop if one were to recursively call `process.nextTick()`. See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. ```js import { nextTick } from 'node:process'; console.log('start'); nextTick(() => { console.log('nextTick callback'); }); console.log('scheduled'); // Output: // start // scheduled // nextTick callback ``` This is important when developing APIs in order to give users the opportunity to assign event handlers _after_ an object has been constructed but before any I/O has occurred: ```js import { nextTick } from 'node:process'; function MyThing(options) { this.setupOptions(options); nextTick(() => { this.startDoingStuff(); }); } const thing = new MyThing(); thing.getReadyForStuff(); // thing.startDoingStuff() gets called now, not before. ``` It is very important for APIs to be either 100% synchronous or 100% asynchronous. Consider this example: ```js // WARNING! DO NOT USE! BAD UNSAFE HAZARD! function maybeSync(arg, cb) { if (arg) { cb(); return; } fs.stat('file', cb); } ``` This API is hazardous because in the following case: ```js const maybeTrue = Math.random() > 0.5; maybeSync(maybeTrue, () => { foo(); }); bar(); ``` It is not clear whether `foo()` or `bar()` will be called first. The following approach is much better: ```js import { nextTick } from 'node:process'; function definitelyAsync(arg, cb) { if (arg) { nextTick(cb); return; } fs.stat('file', cb); } ```
@sincev0.1.26@paramargs Additional arguments to pass when invoking the `callback`
nextTick
(() => {
// do something });

The event loop is busy processing the current function code. When this operation ends, the JS engine runs all the functions passed to nextTick calls during that operation.

It's the way we can tell the JS engine to process a function asynchronously (after the current function), but as soon as possible, not queue it.

Calling setTimeout(() => {}, 0) will execute the function at the end of next tick, much later than when using nextTick() which prioritizes the call and executes it just before the beginning of the next tick.

Use nextTick() when you want to make sure that in the next event loop iteration that code is already executed.

To learn more about the order of execution and how the event loop works, check out the dedicated article

Durată de citire
1 min.
Autori
Contribuie
Editează această pagină