Expand description
Node async_hooks module — honest minimal implementation.
There IS a real async-resource id graph, but only over the resources this module itself creates:
- Every
new AsyncResource(type)takes the next monotonically increasingasyncId(from 2; Node reserves 1 for the root context) and records the creating context’s id as itstriggerAsyncId. runInAsyncScopemakes that pair the current execution context for the duration of the call, soexecutionAsyncId()inside reports the resource and a resource constructed there inherits it as its parent. NestingrunInAsyncScopetherefore builds a real parent chain.
What is NOT modeled: node-js does not instrument timers, promises, sockets
or any other engine-level async resource, so executionAsyncId() inside a
setTimeout/.then callback reports the ROOT context (1) rather than a
per-callback id, and triggerAsyncId() there reports 0. Only the
AsyncResource graph above is real. Consequently:
createHook({ init, before, after, destroy })returns a hook object with chainableenable()/disable(). The registered callbacks are stored nowhere and NEVER FIRE — node-js does not instrument async resource lifetimes. This is intentional; do not treat it as a gap to “fill” by faking hook invocations.
What IS real is AsyncLocalStorage for the SYNCHRONOUS case: run(store, cb)
makes getStore() return store for the duration of cb (and restores the
previous store afterwards), and enterWith(store) sets the current store for
subsequent synchronous getStore() calls. Because there is no async-context
propagation, a store set with enterWith (or visible inside run) does NOT
automatically follow into setTimeout/Promise callbacks — cross-async
propagation is not modeled. Within straight-line synchronous code the store is
correct.
Instances are @@native-tagged objects (AsyncLocalStorage / AsyncHook)
dispatched through instance_call; the parent wires construct,
native_tag, instance_has_method, and instance_call (see the report).
Constants§
- ALS_
METHODS - Instance method names by native tag — for the parent’s
instance_has_methodso a method read (als.run.bind(...)) resolves before it is invoked. - HOOK_
METHODS - METHODS
- Module-level callable members.
- RESOURCE_
METHODS - RESOURCE_
STATIC_ METHODS - Static members on the
AsyncResourceconstructor itself.
Functions§
- call
- construct
- Construct a stdlib class instance (
new AsyncLocalStorage()).Nonefor any other name so the parent’sconstructcan fall through. - execution_
async_ id - The id of the currently-executing async context (Node’s
executionAsyncId). - instance_
call - Dispatch a method on a native
async_hooksinstance. - static_
call AsyncResource.bind(fn[, type[, thisArg]])— with no async-context graph to capture there is nothing to restore, so the bound function ISfn(bound tothisArgwhen one is given). Node’s own semantics reduce to this whenever no context is active.- trigger_
async_ id - The id of the context that created the currently-executing one.