Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

async
javascript

How to use setImmediate(callback) in Async

Nouman Abbasi

setImmediate(callback) is a method provided by the Async module that defers a callback function’s execution until the next event loop iteration.

In Node.js, this is called setImmediate. The browser will use setImmediate if available; otherwise, setTimeout(callback, 0) will be used (this means other higher priority events may precede the execution of the callback function).

Syntax

setImmediate(callback, args...)

  • 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 defer the execution of a function that accepts a name argument and outputs 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 setImmediate().

import setImmediate from 'async/setImmediate';

// Defering the execution of a function.
setImmediate(function(name) {
    // This will run second
    console.log('2.', name);
    
}, 'World');

// This will run first
console.log('1. Hello');

For information on nextTick(callback), a function similar to setImmediate(callback) in the Async module, click here.

RELATED TAGS

async
javascript

CONTRIBUTOR

Nouman Abbasi
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring