Node.js async.queue() Method
How to use async.queue?
- Step 1: Create a package.json file. A package.json file is created by the running the following command.
- 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.
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.
length(): The length method returns the number of elements currently present in the queue. The following code demonstrates how the length method works.
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.
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 :-
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.
Note: The drain method only works when the function described is an arrow function.
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.
resume() Method: The resume method resumes the execution of elements in the queue. The following code demonstrates how the resume method works.
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.
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.
Complete Code: The following code is a complete demonstration of how the async.queue is actually used.