2022-02-02 14:21:39 +00:00
|
|
|
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
|
2021-01-22 11:45:29 +00:00
|
|
|
import { delay } from "./delay.ts";
|
2020-07-29 00:44:34 +00:00
|
|
|
import { pooledMap } from "./pool.ts";
|
2021-01-22 11:45:29 +00:00
|
|
|
import {
|
|
|
|
assert,
|
|
|
|
assertEquals,
|
2021-08-09 05:59:52 +00:00
|
|
|
assertRejects,
|
2021-01-22 11:45:29 +00:00
|
|
|
assertStringIncludes,
|
|
|
|
} from "../testing/asserts.ts";
|
2020-07-29 00:44:34 +00:00
|
|
|
|
2021-04-05 11:49:05 +00:00
|
|
|
Deno.test("[async] pooledMap", async function () {
|
2020-07-29 00:44:34 +00:00
|
|
|
const start = new Date();
|
|
|
|
const results = pooledMap(
|
|
|
|
2,
|
|
|
|
[1, 2, 3],
|
|
|
|
(i) => new Promise((r) => setTimeout(() => r(i), 1000)),
|
|
|
|
);
|
|
|
|
for await (const value of results) {
|
|
|
|
console.log(value);
|
|
|
|
}
|
|
|
|
const diff = new Date().getTime() - start.getTime();
|
|
|
|
assert(diff >= 2000);
|
|
|
|
assert(diff < 3000);
|
|
|
|
});
|
|
|
|
|
2021-04-05 11:49:05 +00:00
|
|
|
Deno.test("[async] pooledMap errors", async function () {
|
2021-01-22 11:45:29 +00:00
|
|
|
async function mapNumber(n: number): Promise<number> {
|
|
|
|
if (n <= 2) {
|
|
|
|
throw new Error(`Bad number: ${n}`);
|
|
|
|
}
|
|
|
|
await delay(100);
|
|
|
|
return n;
|
|
|
|
}
|
|
|
|
const mappedNumbers: number[] = [];
|
2021-08-09 05:59:52 +00:00
|
|
|
await assertRejects(async () => {
|
2021-09-15 15:35:21 +00:00
|
|
|
for await (const m of pooledMap(3, [1, 2, 3, 4], mapNumber)) {
|
|
|
|
mappedNumbers.push(m);
|
2021-01-22 11:45:29 +00:00
|
|
|
}
|
2021-09-15 15:35:21 +00:00
|
|
|
}, (error: Error) => {
|
|
|
|
assert(error instanceof AggregateError);
|
|
|
|
assertEquals(error.errors.length, 2);
|
|
|
|
assertStringIncludes(error.errors[0].stack, "Error: Bad number: 1");
|
|
|
|
assertStringIncludes(error.errors[1].stack, "Error: Bad number: 2");
|
|
|
|
});
|
2021-01-22 11:45:29 +00:00
|
|
|
assertEquals(mappedNumbers, [3]);
|
|
|
|
});
|