Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Node.js fs.read() Method
Next article icon

Node.js async.queue() Method

Last Updated : 11 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

The async module is is designed for working with asynchronous JavaScript in NodeJS. The async.queue returns a queue object which is capable of concurrent processing i.e processing multiple items at a single time.

How to use async.queue?

  • Step 1: Create a package.json file. A package.json file is created by the running the following command. 
     
npm init
  • Step 2: Installing the async module. The async module can be installed using the following command. 
     
npm i async
  • Step 3: Importing the async module. The async module can be imported using the following command. 
     
const async = require('async')
  • Step 4: Using the async.queue module. Syntax of async.queue.
     
const queue = async.queue('function', 'concurrency value')

The parameter function is executed on the element added to the queue. The concurrency value tells the queue, the number of elements to be processed at a particular time.

Example: Have a look at the below example for better understanding.

Javascript

// Defining The queue
const queue = async.queue((task, completed) => {
    // Here task is the current element being
    // processed and completed is the callback function
     
    console.log("Currently Busy Processing Task " + task);
     
    // Simulating a complex process.
    setTimeout(()=>{
        // Number of elements to be processed.
        const remaining = queue.length();
        completed(null, {task, remaining});
    }, 1000);
 
}, 1);
 
// The concurrency value is set to one,
// Which means that one element is being
// Processed at a particular time
                      
                       

 

 

Important methods and properties in async.queue:


 

push(element, callback) :The push method is used to add elements to the tail of the queue. The following code demonstrates how push method works.


  1.  

Javascript

// Takes in two parameters, the item being pushed and
// the callback function
// Here the item is the element being added
// and other is the callback function with error
// and data property(destructured)
 
queue.push(item, (error, {item, remaining}) => {
  if(error){
      console.log(`An error occurred while processing task ${task}`);
  } else {
      console.log(`Finished processing task ${task}
             . ${remaining} tasks remaining`);
  }
});
                      
                       
  1.  
     

length(): The length method returns the number of elements currently present in the queue. The following code demonstrates how the length method works.


  1.  

Javascript

console.log(queue.length());
                      
                       
  1.  
     

started property: The started property returns a boolean value, indicating whether the queue has started processing the data or not. The following code demonstrates how the started property works.


  1.  

Javascript

// Returns true if the queue has started processing the data else false
console.log(queue.started)
                      
                       
  1.  
     

unshift(element, callback) :The unshift method is similar to the push method, but the element is added to the head of the queue, indicating that the element to be processed is an important one. The following code demonstrates how the unshift method works :-


  1.  

Javascript

// Takes in two parameters, the item being pushed
// and the callback function
// Here the item is the element being added
// and other is the callback function with error
// and data property(destructured)
 
queue.unshift(item, (error, {item, remaining}) => {
  if(error){
   console.log(`An error occurred while processing task ${task}`);
  } else {
   console.log(`Finished processing task ${task}. ${remaining} tasks remaining`);
  }
});
                      
                       
  1.  
     

drain() Method : The drain method runs a callback function when the queue is done executing all the tasks. The following code demonstrates how the drain method works.


  1.  

Note: The drain method only works when the function described is an arrow function.


  1.  

Javascript

// Executes when the queue is done processing all the items
queue.drain(() => {
    console.log('Successfully processed all items');
})
                      
                       

  1.  

pause() Method : The pause method pauses the execution of elements in the queue until the resume function is called. The following code demonstrates how the pause method works.


  1.  

Javascript

// Pauses the execution of the queue
queue.pause()
                      
                       
  1.  
     

resume() Method: The resume method resumes the execution of elements in the queue. The following code demonstrates how the resume method works.


  1.  

Javascript

// Resumes the execution of the queue
queue.resume()
                      
                       
  1.  
     

kill() Method: The kill method removes all the elements from the queue, the callback function of the drain method and forces it into idle. The following code demonstrates how the kill method works.


  1.  

Javascript

// Forces the queue into idle mode
// and removes the drain callback
queue.kill()
                      
                       
  1.  
     

idle() Method: The idle() method return a boolean value, indicating whether the queue is idle or processing something. The following code demonstrates how the idle method works.


  1.  

Javascript

// Returns whether the queue is idle or not
queue.idle()
                      
                       
  1.  
     


 

Complete Code: The following code is a complete demonstration of how the async.queue is actually used.


 

Javascript

// Importing the async module
const async = require('async');
 
// Creating a tasks array
const tasks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
// Defining the queue
const queue = async.queue((task, completed) => {
    console.log("Currently Busy Processing Task " + task);
     
    // Simulating a Complex task
    setTimeout(()=>{
        // The number of tasks to be processed
        const remaining = queue.length();
        completed(null, {task, remaining});
    }, 1000);
 
}, 1); // The concurrency value is 1
 
 
// The queue is idle as there are no elements
// for the queue to process
console.log(`Did the queue start ? ${queue.started}`)
 
// Adding the each task to the queue
tasks.forEach((task)=>{
 
    // Adding the 5th task to the head of the
    // queue as it is deemed important by us
 if(task == 5){
    queue.unshift(task, (error, {task, remaining})=>{
      if(error){
       console.log(`An error occurred while processing task ${task}`);
      }else {
       console.log(`Finished processing task ${task}. ${remaining} tasks remaining`);
      }
    })     
        // Adding the task to the tail in the order of their appearance
 } else {
      queue.push(task, (error, {task, remaining})=>{
       if(error){
        console.log(`An error occurred while processing task ${task}`);
       }else {
        console.log(`Finished processing task ${task}. ${remaining} tasks remaining`);
      }
      })
    }
});
 
 
// Executes the callback when the queue is done processing all the tasks
queue.drain(() => {
    console.log('Successfully processed all items');
})
 
// The queue is not idle it is processing the tasks asynchronously
console.log(`Did the queue start ? ${queue.started}`)
                      
                       

 

 

Output:


 


 



Next Article
Node.js fs.read() Method
author
coder_srinivas
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • Node.js-Methods

Similar Reads

  • Node.js fs.fsync() Method
    In Node, the 'fs' module provides an API for interacting with the file system in a manner closely modeled around standard Portable Operating System Interface (POSIX) functions. It has both synchronous and asynchronous forms. The asynchronous form always takes a completion callback as its last argume
    2 min read
  • Node.js fs.read() Method
    Node.js is used for server-side scripting. Reading and writing files are the two most important operations that are performed in any application. Node.js offers a wide range of inbuilt functionalities to perform read and write operations. The fs package contains the functions required for file opera
    3 min read
  • Node.js fs.fdatasync() Method
    The fs module provides an API for interacting with the file-system in a manner closely modeled around standard POSIX functions. All the file system operations have synchronous and asynchronous forms and mostly the asynchronous form takes a completion callback as its last argument. The fs.fdatasync()
    2 min read
  • 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 i
    2 min read
  • Node JS fs.readFile() Method
    ​In Node.js, the fs.readFile() method is a fundamental tool for reading files asynchronously, allowing your application to remain responsive while accessing file data. This method is part of Node.js's File System (fs) module, which provides an API for interacting with the file system. Syntaxfs.readF
    4 min read
  • Node.js fs.fsyncSync() Method
    In this article, we will be learning about fsyncSync() method in NodeJS. Before diving deep into the topic, let's have a brief idea about what a fsync() method is. Node.js provides us with a 'fs' module that helps us with both synchronous and asynchronous forms. An asynchronous form has a callback a
    2 min read
  • Node JS fs.writeFile() Method
    ​In Node.js, the fs.writeFile() method is a built-in function used to asynchronously write data to a file. This method allows you to create a new file or overwrite an existing one with the specified content, without blocking the event loop, thus maintaining the non-blocking nature of Node.js applica
    4 min read
  • Node.js fs.closeSync() Method
    The fs.closeSync() method is used to synchronously close the given file descriptor thereby clearing the file that is associated with it. It allows the file descriptor to be reused for other files. Calling fs.closeSync() on a file descriptor while some other operation is being performed on it may lea
    2 min read
  • Node.js fs.fdatasyncSync() Method
    The fs(File System) module enables interacting with the file system in a way modeled on standard POSIX functions, which means we can perform I/O operations with our Computer's file System. Like reading data from a file, writing data to a file, etc. All the file system operations have synchronous and
    2 min read
  • Node.js util.types.isAsyncFunction() Method
    The util.types.isAsyncFunction() method is an inbuilt application programming interface of the util module which is used to type check for asynchronous functions in the node.js. Syntax:  util.types.isAsyncFunction( value ) Parameters: This method accepts a single parameter as mentioned above and des
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences