go-like-ctx
v0.1.1
Published
Go-style context discipline for Node.js
Readme
go-like-ctx
Go-style context discipline for Node.js. Explicit context passing, cooperative cancellation, zero runtime deps.
Example
import { background } from "go-like-ctx";
async function runJob() {
const jobCtx = background().withTimeout(2000);
const step1 = jobCtx.withCancel();
const step2 = jobCtx.withCancel();
const work = async (ctx: ReturnType<typeof background>) => {
await fetch("https://example.com", { signal: ctx.signal() });
ctx.throwIfCancelled();
};
await Promise.all([work(step1), work(step2)]);
}API
background()creates a root context.ctx.withCancel()creates a child context.ctx.withTimeout(ms)creates a child context with a deadline.ctx.withValue(key, value)creates a child context carrying a value.ctx.cancel()cancels the context; children observe it.ctx.done()returns a promise that resolves on cancellation.ctx.cancelled()returns a boolean cancellation flag.ctx.throwIfCancelled()throwsContextCancelledErrorif cancelled.ctx.signal()returns anAbortSignalfor integrations.ctx.value(key)walks the parent chain to resolve a value.
Go comparison
Background
ctx := context.Background()const ctx = background();WithCancel
ctx, cancel := context.WithCancel(parent)
defer cancel()const ctx = parent.withCancel();
// call ctx.cancel() when you want to stop the treeWithTimeout
ctx, cancel := context.WithTimeout(parent, 2*time.Second)
defer cancel()const ctx = parent.withTimeout(2000);WithValue
ctx := context.WithValue(parent, key, value)
val := ctx.Value(key)const ctx = parent.withValue(key, value);
const val = ctx.value(key);Done
<-ctx.Done()await ctx.done();Cancelled / Err
if ctx.Err() != nil {
// context.Canceled or context.DeadlineExceeded
}if (ctx.cancelled()) {
// ContextCancelledError semantics
}ThrowIfCancelled / Err
if err := ctx.Err(); err != nil {
return err
}ctx.throwIfCancelled();Signal (integration escape hatch)
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)await fetch(url, { signal: ctx.signal() });Notes:
- Go uses
Done() <-chan struct{}andErr(), Node usesdone(): Promise<void>andcancelled()/throwIfCancelled(). - Go exposes
context.Contextonly; this library exposesContextwith explicitcancel(). - Cancellation is always parent -> child in both Go and this library.
