最近给我的 yimuc.com 整了个工具集的新功能,在搜寻工具库的时候发现了这个库async-pool。我自己工具站地址是这个:job.yimuc.com/online/toolkit ,介意的请不要点过去哈,浪费你时间。
重点在这里,先上个 Github 电梯直达: https://github.com/rxaviers/async-pool/blob/master/lib/es9.js
不跳转也行,整个库就只有这一段代码,代码我也直接贴下面:
async function* asyncPool(concurrency, iterable, iteratorFn) {
const executing = new Set();
async function consume() {
const [promise, value] = await Promise.race(executing);
executing.delete(promise);
return value;
}
for (const item of iterable) {
// Wrap iteratorFn() in an async fn to ensure we get a promise.
// Then expose such promise, so it's possible to later reference and
// remove it from the executing pool.
const promise = (async () => await iteratorFn(item, iterable))().then(
value => [promise, value]
);
executing.add(promise);
if (executing.size >= concurrency) {
yield await consume();
}
}
while (executing.size) {
yield await consume();
}
}
module.exports = asyncPool;
感觉这样处理很优雅啊,代码也很简洁。因为我正常写业务代码很少用generator function的,所以看了会觉得很新颖,他这里用了Promise、async await、generator function,外层调用它的时候还可以用for await()。
学到了~