-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimeout-stop.sample.js
More file actions
48 lines (42 loc) · 1.15 KB
/
timeout-stop.sample.js
File metadata and controls
48 lines (42 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Timeout cancellation sample.
*
* @author Admilson B. F. Cossa
* SPDX-License-Identifier: Apache-2.0
*
* Proves timeout wrappers actually abort signal-aware work, not just reject
* while the original operation keeps running.
*/
import assert from "node:assert/strict";
import { CancellationError, TimeoutError, group, run } from "../dist/index.js";
let stopped = false;
let reasonKind;
await assert.rejects(
group(async (task) => task(run.timeout(async (ctx) => {
try {
await sleep(1_000, ctx.signal);
return "late";
} catch (err) {
stopped = true;
if (err instanceof CancellationError) reasonKind = err.reason.kind;
throw err;
}
}, "10ms"), { name: "timeout.provider" })),
TimeoutError
);
assert.equal(stopped, true);
assert.equal(reasonKind, "timeout");
process.stdout.write(`${JSON.stringify({
sample: "timeout-stop",
stopped,
reasonKind,
})}\n`);
function sleep(ms, signal) {
return new Promise((resolve, reject) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener("abort", () => {
clearTimeout(timer);
reject(signal.reason);
}, { once: true });
});
}