forked from unjs/unenv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_async-resource.ts
63 lines (53 loc) · 1.55 KB
/
_async-resource.ts
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import type asyncHooks from "node:async_hooks";
import { executionAsyncId } from "./_async-hook";
// https://nodejs.org/api/async_context.html#class-asyncresource
let _asyncIdCounter = 100;
export class AsyncResource implements asyncHooks.AsyncResource {
type: string;
_asyncId: undefined | number;
_triggerAsyncId: undefined | number | asyncHooks.AsyncResourceOptions;
constructor(
type: string,
triggerAsyncId:
| number
| asyncHooks.AsyncResourceOptions = executionAsyncId()
) {
this.type = type;
this._asyncId = -1 * _asyncIdCounter++;
this._triggerAsyncId =
typeof triggerAsyncId === "number"
? triggerAsyncId
: triggerAsyncId?.triggerAsyncId;
}
static bind<Func extends (this: ThisArg, ...args: any[]) => any, ThisArg>(
fn: Func,
type?: string,
thisArg?: ThisArg
) {
const resource = new AsyncResource(type ?? "anonymous");
return resource.bind(fn, thisArg);
}
bind<Func extends (...args: any[]) => any>(fn: Func, thisArg?: any) {
const binded = (...args: any[]) =>
this.runInAsyncScope(fn, thisArg, ...args);
binded.asyncResource = this;
return binded as any;
}
runInAsyncScope<This, Result>(
fn: (this: This, ...args: any[]) => Result,
thisArg?: This,
...args: any[]
): Result {
const result = fn.apply(thisArg as This, args);
return result;
}
emitDestroy(): this {
return this;
}
asyncId(): number {
return this._asyncId as number;
}
triggerAsyncId(): number {
return this._triggerAsyncId as number;
}
}