异步模块旨在与NodeJS中的异步JavaScript一起使用。 async.queue返回一个队列对象,该对象能够并发处理,即一次处理多个项目。
如何使用async.queue?
- 第1步:创建一个package.json文件。通过运行以下命令来创建package.json文件。
npm init
- 第2步:安装异步模块。可以使用以下命令安装异步模块。
npm i async
- 第三步:导入异步模块。可以使用以下命令导入异步模块。
const async = require('async')
- 第四步:使用async.queue模块。 async.queue的语法。
const queue = async.queue('function', 'concurrency value')
参数函数在添加到队列的元素上执行。并发值告诉队列在特定时间要处理的元素数。
例:请看以下示例,以更好地理解。
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 elemets 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
async.queue中的重要方法和属性:
push(element,callback):push方法用于将元素添加到队列的尾部。以下代码演示了push方法的用法方式。
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`); } });
length():length方法返回队列中当前存在的元素数。以下代码演示了length方法的用法方式。
Javascript
console.log(queue.length());
starts属性:starts属性返回一个布尔值,该值指示队列是否已开始处理数据。以下代码演示了启动属性的工作方式。
Javascript
// Returns true if the queue has started processing the data else false console.log(queue.started)
unshift(element,callback):unshift方法类似于push方法,但是该元素已添加到队列的开头,表明要处理的元素是重要的元素。以下代码演示了unshift方法的用法原理:-
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`); } });
drain()方法:当队列执行完所有任务后,drain方法将运行回调函数。下面的代码演示了rain方法的用法方式。
注意:仅当描述的函数是箭头函数时,排水方法才有效。
Javascript
// Executes when the queue is done processing all the items queue.drain(() => { console.log('Successfully processed all items'); })
pause()方法:暂停方法暂停队列中元素的执行,直到调用恢复函数为止。以下代码演示了pause方法的用法方式。
Javascript
// Pauses the execution of the queue queue.pause()
resume()方法:resume方法恢复队列中元素的执行。以下代码演示了resume方法的用法方式。
Javascript
// Resumes the execution of the queue queue.resume()
kill()方法:kill方法从队列中删除所有元素,并删除掉方法的回调函数并将其强制为空闲。以下代码演示kill方法的用法方式。
Javascript
// Forces the queue into idle mode // and removes the drain callback queue.kill()
idle()方法:idle()方法返回一个布尔值,指示队列是空闲还是正在处理某些内容。以下代码演示了idle方法的用法方式。
Javascript
// Returns whether the queue is idle or not queue.idle()
完整的代码:以下代码完整演示了async.queue的实际使用方式。
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}`)
输出:
相关用法
- Node.js console.timeLog()用法及代码示例
- Node.js fs.fsyncSync()用法及代码示例
- Node.js process.nextTick()用法及代码示例
- Node.js x509.toLegacyObject()用法及代码示例
- Node.js GM charcoal()用法及代码示例
- Node.js GM blur()用法及代码示例
- Node.js GM sharpen()用法及代码示例
- Node.js GM drawLine()用法及代码示例
- Node.js GM drawArc()用法及代码示例
- Node.js GM drawPolyline()用法及代码示例
- Node.js GM drawBezier()用法及代码示例
注:本文由纯净天空筛选整理自coder_srinivas大神的英文原创作品 Node.js async.queue() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。