async-pool/lib/es7.js
Matthias 1e7f18aca0
Avoid UnhandledPromiseRejectionWarning (#18)
* Remove test that fails after commit #3114536
* Fix prettier command
* Improve tests for error handling

Fixes #9
2020-08-05 09:06:25 -03:00

32 lines
848 B
JavaScript

let assert, assertType;
const shouldAssert = process.env.NODE_ENV === "development";
if (shouldAssert) {
({ assert, assertType } = require("yaassertion"));
}
async function asyncPool(poolLimit, array, iteratorFn) {
if (shouldAssert) {
assertType(poolLimit, "poolLimit", ["number"]);
assertType(array, "array", ["array"]);
assertType(iteratorFn, "iteratorFn", ["function"]);
}
const ret = [];
const executing = [];
for (const item of array) {
const p = Promise.resolve().then(() => iteratorFn(item, array));
ret.push(p);
if (poolLimit <= array.length) {
const e = p.then(() => executing.splice(executing.indexOf(e), 1));
executing.push(e);
if (executing.length >= poolLimit) {
await Promise.race(executing);
}
}
}
return Promise.all(ret);
}
module.exports = asyncPool;