Trusted answers to developer questions

How to use nextTick(callback) in Async

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

nextTick(callback) is a method provided by the Async module that defers the execution of a function until the next event loop iteration. Similar to how the setTimeout() is used in browsers to defer execution of a function by a given time, nextTick() defers execution until the next tick.

In Node.js, each iteration of an event loop is called a tick.

In Node.js, nextTick() just calls process.nextTick. In the browser, it will use setImmediate if available, otherwise it will use setTimeout(callback, 0), which means that the other higher priority events may precede the execution of the callback function.

Syntax

The function signature is as follows:

nextTick(callback, arg...)

  • callback: The function to call on a later loop around the event loop
  • args...: (Optional) Additional arguments to pass to the callback

Example

In this example, we simply defer the execution of a function that accepts a name argument and output that name to the console.

Notice that the statement console.log('1. Hello') runs before the statement console.log('2.', name) inside the callback function passed to nextTick().

import nextTick from 'async/nextTick';
// Defering the execution of a function.
nextTick(function(name) {
// This will run second
console.log('2.', name);
}, 'World');
// This will run first
console.log('1. Hello');

RELATED TAGS

javascript

CONTRIBUTOR

Nouman Abbasi
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?