typed-utilities
Version:
Strongly typed general purpose utilities
77 lines (56 loc) • 2.23 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.resolveAllSerial = exports.resolveAllConcurrent = exports.mapEntriesAsyncSerial = exports.mapEntriesAsyncConcurrent = exports.mapAsyncSerial = exports.mapAsyncConcurrent = void 0;
var _AsyncSemaphore = require("./AsyncSemaphore");
var _id = require("./id");
const mapAsyncSerial = async (items, fn) => {
const values = [];
const errors = [];
for (const item of items) {
try {
values.push(await fn(item));
} catch (error) {
errors.push(error);
}
}
if (errors.length > 0) {
throw new AggregateError(errors);
}
return values;
};
exports.mapAsyncSerial = mapAsyncSerial;
const mapAsyncConcurrent = async (items, fn, opts) => {
const values = [];
const errors = [];
const semaphore = new _AsyncSemaphore.AsyncSemaphore((opts === null || opts === void 0 ? void 0 : opts.maxConcurrency) ?? items.length + 1);
const results = await Promise.allSettled(items.map(async item => semaphore.use(() => fn(item))));
for (const result of results) {
if (result.status === `fulfilled`) {
values.push(result.value);
} else {
errors.push(result.reason);
}
}
if (errors.length > 0) {
throw new AggregateError(errors);
}
return values;
};
exports.mapAsyncConcurrent = mapAsyncConcurrent;
const mapEntriesAsyncConcurrent = async (entries, opts) => {
const resolvedEntries = await resolveAllConcurrent(Object.entries(entries).map(async ([key, value]) => [key, await value]), opts);
return Object.fromEntries(resolvedEntries);
};
exports.mapEntriesAsyncConcurrent = mapEntriesAsyncConcurrent;
const mapEntriesAsyncSerial = async entries => {
const resolvedEntries = await resolveAllSerial(Object.entries(entries).map(async ([key, value]) => [key, await value]));
return Object.fromEntries(resolvedEntries);
};
exports.mapEntriesAsyncSerial = mapEntriesAsyncSerial;
const resolveAllSerial = values => mapAsyncSerial(values, _id.id);
exports.resolveAllSerial = resolveAllSerial;
const resolveAllConcurrent = (values, opts) => mapAsyncConcurrent(values, _id.id, opts);
exports.resolveAllConcurrent = resolveAllConcurrent;
//# sourceMappingURL=iterAsync.js.map