Horje
Node.js queueMicrotask() Method

The queueMicrotask() method in Node.js allows you to queue a function to be performed asynchronously as soon as the current code block is finished. This method only accepts one parameter, the function to be queued. The microtask is a temporary function that runs after the current task has finished its job and there is no other code waiting to be executed before control of the execution context is returned to the browser’s event loop.

Syntax:

queueMicrotask(function);

Parameters: This method accepts a single parameter that is described below:

  • function: A new function for the microtask queue. When the current call stack has been emptied, this method will be run asynchronously.

Return Value: This method returns undefined value.

Example 1: Using queueMicrotask() to execute a function after the current call stack has cleared.

Javascript

console.log('start');
  
queueMicrotask(() => {
    console.log('executing microtask');
});
  
console.log('end');

Steps to run: Run the index.js file using the following command:

node index.js

Output:

NodeJS queueMicrotask() Method

NodeJS queueMicrotask() Method

Example 2: Using queueMicrotask() to create a simple task queue.

Javascript

const taskQueue = [];
  
function addToTaskQueue(task) {
    taskQueue.push(task);
    queueMicrotask(processTaskQueue);
}
  
function processTaskQueue() {
    const task = taskQueue.shift();
    if (task) {
        task();
        queueMicrotask(processTaskQueue);
    }
}
  
function logTask(text) {
    return () => console.log(text);
}
  
addToTaskQueue(logTask('Task 1'));
addToTaskQueue(logTask('Task 2'));
addToTaskQueue(logTask('Task 3'));

Run the index.js file using the following command:

node index.js

Output:

NodeJS queueMicrotask() Method

 queueMicrotask() Method

Reference: https://nodejs.org/api/globals.html#queuemicrotaskcallback




Reffered: https://www.geeksforgeeks.org


Node.js

Related
Node.js Process unhandledRejection Event Node.js Process unhandledRejection Event
Mongoose Plugins Mongoose Plugins
How to Create API to View Logs in Node.js ? How to Create API to View Logs in Node.js ?
Node.js keyObject.equals() Method Node.js keyObject.equals() Method
Mongoose SchemaType.prototype.index() API Mongoose SchemaType.prototype.index() API

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
10