@dxos/util 0.3.11-next.ee2b64c → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/defer.ts ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Run function on scope exit.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * {
7
+ * using _ = defer(() => console.log('exiting'));
8
+ *
9
+ * ...
10
+ * }
11
+ */
12
+ //
13
+ // Copyright 2024 DXOS.org
14
+ //
15
+
16
+ export const defer = (fn: () => void): Disposable => new DeferGuard(fn);
17
+
18
+ class DeferGuard {
19
+ /**
20
+ * @internal
21
+ */
22
+ constructor(private readonly _fn: () => void) {}
23
+
24
+ [Symbol.dispose]() {
25
+ const result = this._fn();
26
+ if ((result as any) instanceof Promise) {
27
+ throw new Error('Async functions in defer are not supported. Use deferAsync instead.');
28
+ }
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Run async function on scope exit.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * {
38
+ * await using _ = deferAsync(async () => console.log('exiting'));
39
+ *
40
+ * ...
41
+ * }
42
+ */
43
+ export const deferAsync = (fn: () => Promise<void>): AsyncDisposable => new DeferAsyncGuard(fn);
44
+
45
+ class DeferAsyncGuard implements AsyncDisposable {
46
+ /**
47
+ * @internal
48
+ */
49
+ constructor(private readonly _fn: () => Promise<void>) {}
50
+
51
+ async [Symbol.asyncDispose]() {
52
+ await this._fn();
53
+ }
54
+ }
package/src/index.ts CHANGED
@@ -28,3 +28,4 @@ export * from './sum';
28
28
  export * from './for-each-async';
29
29
  export * from './weak';
30
30
  export * from './map-values';
31
+ export * from './defer';