【问题标题】:An analog of async.queue for Async/Await functions用于 Async/Await 函数的 async.queue 的模拟
【发布时间】:2018-10-09 19:01:59
【问题描述】:

我正在对一些代码进行现代化改造。它有一块加载数据库实现为:

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,对吧?

【问题讨论】:

  • 您编写此代码的方式基本上将运行您的processQueue 同步,即使它是使用async 承诺执行的。 Promise.all(q) 将正确执行,但 for () 的每次迭代都将暂停,直到 Promise.all(q) 返回。这是你想要的吗?
  • @Deryck 同步 != 顺序。
  • "语法不好,我为每个队列保留了一个可见的命名变量" - 你应该能够通过将整个东西包装在一个 (module factory) 函数,它只返回(导出)你需要使用队列的东西。
  • 上下文只是为了引起他的注意,以防他认为循环会像使用旧代码并转换为新的async/await 时那样毫无延迟地继续进行。
  • JavaScript 只有一个线程。因此,没有什么是真正并行运行的。我相信这个东西,如果我了解async.queue 的工作原理,将创建parallelism 数量的异步请求,就像原来的一样。一旦这些都完成了,它将再次运行这个东西。你熟悉async 包吗?我错了吗?

标签: javascript asynchronous async-await ecmascript-2017


【解决方案1】:

@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 创建一个实例,并使用单独的 e.g. “本地”队列。然后,它基本上会像原来的那样工作。

我会随着进度更新。

【讨论】:

    猜你喜欢
    • 2018-07-20
    • 2018-08-28
    • 2021-08-06
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 2016-01-22
    相关资源
    最近更新 更多