@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/dist/lib/browser/index.mjs +31 -0
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node/index.cjs +31 -0
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/meta.json +1 -1
- package/dist/types/src/defer.d.ts +25 -0
- package/dist/types/src/defer.d.ts.map +1 -0
- package/dist/types/src/defer.test.d.ts +2 -0
- package/dist/types/src/defer.test.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +1 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/package.json +6 -6
- package/src/defer.test.ts +37 -0
- package/src/defer.ts +54 -0
- package/src/index.ts +1 -0
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