Node.js 中的 async.queue() 方法


async 模組提供了不同的功能來處理 Node.js 應用程式中的非同步 JavaScript。async.queue() 方法返回一個佇列,該佇列進一步用於併發處理程序,即一次/瞬間處理多個專案。

安裝和使用 async.queue()

步驟 1 - 執行以下命令初始化節點包管理器。

npm init

步驟 2 - 使用以下命令安裝 async 模組。

npm install --save async

步驟 3 - 在您的程式中使用以下語句匯入 async 模組。

const async = require('async')

語法

async.queue('function', 'concurrency value')

引數

以上引數描述如下:

  • function – 此引數定義將在新增到佇列的元素上執行的函式。

  • 併發值 – 此欄位定義一次要處理的元素數量。

async.queue() 方法還有多個方法和屬性,這些方法和屬性將在處理非同步請求時使用。

  • push(element, callback) - 與普通佇列類似,push 方法用於在佇列的尾部新增元素。

queue.push(item, callback);
  • length() - length 方法用於返回佇列中一次存在的元素數量。

queue.length()
  • started 屬性 - 此屬性返回一個布林值,提供有關佇列的資訊,即它是否已開始處理其元素。

queue.started()
  • unshift(element, callback) - unshift 屬性也像 push() 方法一樣向佇列新增元素。兩者之間的唯一區別是 - 它在頭部新增元素,而 push 在尾部新增元素。此方法用於優先順序元素。

queue.unshift(item, callback)
  • drain() 方法 - 當佇列執行完所有任務/元素時,此方法會發出回撥。它僅在函式以箭頭函式形式描述時才有效。

queue.drain(() => {
   console.log(“All Tasks are completely executed...”);
}
  • pause() 方法 此方法會暫停佇列中剩餘元素的執行。在呼叫 resume() 後,函式將繼續執行。

queue.pause()
  • resume() 方法 - 此方法用於恢復使用 pause() 方法暫停的元素的執行。

queue.resume()
  • kill() 方法 - 此方法會從佇列中刪除所有剩餘元素,並將其強制置於空閒狀態。

queue.kill()
  • idle() 方法 - 此方法返回一個布林狀態,指示佇列是空閒還是正在處理某些內容。

queue.idle

示例

讓我們看一個示例,以更好地理解上述概念:

// Including the async module
const async = require('async');

// Creating an array for all elements execution
const tasks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Initializing the queue
const queue = async.queue((task, executed) => {
   console.log("Currently Busy Processing Task " + task);

   setTimeout(()=>{
      // Number of tasks remaining and to be processed
      const tasksRemaining = queue.length();
      executed(null, {task, tasksRemaining});
   }, 1000);

}, 1); // concurrency value = 1

// Queue is idle initially as no elements are there...
console.log(`Queue Started ? ${queue.started}`)

// Adding each task from the tasks list
tasks.forEach((task)=>{

   // Adding the task 5 to the head for priority execution
   if(task == 5){
      queue.unshift(task, (error, {task, tasksRemaining})=>{
         if(error){
            console.log(`An error occurred while processing task ${task}`);
         }else {
            console.log(`Finished processing task ${task}. ${tasksRemaining} tasks remaining`);
         }
      })
      // Adding all the tasks at tail to be executed except task 5
   } else {
      queue.push(task, (error, {task, tasksRemaining})=>{
         if(error){
            console.log(`An error occurred while processing task ${task}`);
         }else {
            console.log(`Finished processing task ${task}. ${tasksRemaining}
            tasks remaining`);
         }
      })
   }
});

// Executes the callback when the queue is done processing all the tasks
queue.drain(() => {
   console.log('All items are succesfully processed !');
})

// Checking if the queue is started after adding tasks
console.log(`Queue Started ? ${queue.started}`)

輸出

C:\home
ode>> node asyncQueue.js Queue Started ? False Queue Started ? True Currently Busy Processing Task 5 Finished processing task 5. 9 tasks remaining Currently Busy Processing Task 1 Finished processing task 1. 8 tasks remaining Currently Busy Processing Task 2 Finished processing task 2. 7 tasks remaining Currently Busy Processing Task 3 Finished processing task 3. 6 tasks remaining Currently Busy Processing Task 4 Finished processing task 4. 5 tasks remaining Currently Busy Processing Task 6 Finished processing task 6. 4 tasks remaining Currently Busy Processing Task 7 Finished processing task 7. 3 tasks remaining Currently Busy Processing Task 8 Finished processing task 8. 2 tasks remaining Currently Busy Processing Task 9 Finished processing task 9. 1 tasks remaining Currently Busy Processing Task 10 Finished processing task 10. 0 tasks remaining All items are succesfully processed !

更新於: 2021年5月20日

4K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.