簡體   English   中英

Async / queue函數的async.queue類似物

[英]An analog of async.queue for Async/Await functions

我正在現代化一些代碼。 它具有加載數據庫的一部分,實現為:

var customerQueue = async.queue(insertCustomer, DATABASE_PARALLELISM);
customerQueue.drain = function() {
    logger.info('all customers loaded');
    airportCodeMappingQueue.push(airportCodeMappings);
}

該函數insertCustomer用於編寫回調。 我將其更改為async / await ,作為代碼現代化的一部分。

現在,以為我寫了一個相當於async.queue的代碼:

let customerQueueElements = [];
var customerQueue = {};
customerQueue.push = (customers) => {
  customers.forEach(customer => {
    customerQueueElements.push(insertCustomer(customer))
  });
}

const processQueue = async (queue, parallelism) => {
  for (let i = 0; i < queue.length; i += parallelism) {
    for (let j = 0; j < parallelism; j++) {
      let q = []
      if (queue[i + j]) {
        q.push(queue[i + j])
      }
      await Promise.all(q)
    }
  }
}

現在,我可以await ProcessQueue(customerQueue, DATABASE_PARALLELISM) ,但是語法不好,並且我為每個隊列保留了一個可見的命名變量。

什么是處理此問題的好方法?

另外, drain()應該連接到then ,對嗎?

就方向而言,@ Bergi是正確的。 我整理了一個在制品版本:

module.exports = function () {
  module.internalQueue = []
  module.func = undefined
  module.parallelism =  1

  const process = async () => {
    for (let i = 0; i < module.internalQueue.length; i += module.parallelism) {
      for (let j = 0; j < module.parallelism; j++) {
        let q = []
        if (module.internalQueue[i + j]) {
          q.push(module.func(module.internalQueue[i + j]))
        }
        await Promise.all(q)
      }
    }
    module.internalQueue = []
    module.drain()
  }

  module.queue = (func, parallelism = 1) => {
    module.func = func
    module.parallelism = parallelism
    return module
  }

  module.push = async (customers) => {
    module.internalQueue.push(customers)
    await process()
  }

  module.drain = () => {}

  return module
}

這還不是完全正確。 簽名類似於async包,但是我的版本在所有實例之間共享隊列。

需要找出一種簡單的方法為每個function創建一個帶有單獨的例如“本地”隊列的實例。 然后,它將基本上像原始版本一樣工作。

會隨着我的進步而更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM