異步模塊旨在與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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。