@6river/context 中文文档教程
Context
这是 Go conext 库的基于承诺的端口。
包上下文定义了上下文类型,它携带截止日期、取消信号和其他跨 API 边界的请求范围的值。
对服务的传入请求应该创建一个上下文,对服务的传出调用应该接受一个上下文。 它们之间的函数调用链必须传播 Context,可选择将其替换为使用 withCancel、withDeadline、withTimeout 或 withValue 创建的派生 Context。 当一个上下文被取消时,从它派生的所有上下文也被取消。
withCancel、withDeadline 和 withTimeout 函数接受一个 Context(父级)并返回一个派生的 Context(子级)和一个 CancelFunc。 调用 CancelFunc 会取消子项及其子项,删除父项对子项的引用,并停止任何关联的计时器。 未能调用 CancelFunc 会泄漏子级及其子级,直到父级被取消或计时器触发。
使用 Contexts 的程序应该遵循这些规则,以保持接口在包之间的一致性,并启用静态分析工具来检查上下文传播:
不要将 Contexts 存储在结构类型中; 相反,将 Context 显式传递给需要它的每个函数。 Context 应该是第一个参数,通常命名为 ctx:
function doSomething(ctx: context.Context, arg: Arg) { // ... 使用 ctx ... 仅
将上下文值用于传输进程和 API 的请求范围的数据,而不是将可选参数传递给函数。
Context
This is a promise-based port of Go conext library.
Package context defines the Context type, which carries deadlines, cancelation signals, and other request-scoped values across API boundaries.
Incoming requests to a service should create a Context, and outgoing calls to service should accept a Context. The chain of function calls between them must propagate the Context, optionally replacing it with a derived Context created using withCancel, withDeadline, withTimeout, or withValue. When a Context is canceled, all Contexts derived from it are also canceled.
The withCancel, withDeadline, and withTimeout functions take a Context (the parent) and return a derived Context (the child) and a CancelFunc. Calling the CancelFunc cancels the child and its children, removes the parent's reference to the child, and stops any associated timers. Failing to call the CancelFunc leaks the child and its children until the parent is canceled or the timer fires.
Programs that use Contexts should follow these rules to keep interfaces consistent across packages and enable static analysis tools to check context propagation:
Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it. The Context should be the first parameter, typically named ctx:
function doSomething(ctx: context.Context, arg: Arg) { // … use ctx … }
Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions.