【发布时间】: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