nstdlib-nightly
Version:
Node.js standard library converted to runtime-agnostic ES modules.
44 lines (34 loc) • 991 B
JavaScript
// Source: https://github.com/nodejs/node/blob/65eff1eb/lib/internal/async_local_storage/async_context_frame.js
import * as AsyncContextFrame from "nstdlib/lib/internal/async_context_frame";
import { AsyncResource } from "nstdlib/lib/async_hooks";
class AsyncLocalStorage {
static bind(fn) {
return AsyncResource.bind(fn);
}
static snapshot() {
return AsyncLocalStorage.bind((cb, ...args) => cb(...args));
}
disable() {
AsyncContextFrame.disable(this);
}
enterWith(data) {
const frame = new AsyncContextFrame(this, data);
AsyncContextFrame.set(frame);
}
run(data, fn, ...args) {
const prior = AsyncContextFrame.current();
this.enterWith(data);
try {
return ReflectApply(fn, null, args);
} finally {
AsyncContextFrame.set(prior);
}
}
exit(fn, ...args) {
return this.run(undefined, fn, ...args);
}
getStore() {
return AsyncContextFrame.current()?.get(this);
}
}
export default AsyncLocalStorage;