{"id":13736782,"url":"https://github.com/code-hex/deno-context","last_synced_at":"2025-04-10T23:14:05.357Z","repository":{"id":62420944,"uuid":"264393234","full_name":"Code-Hex/deno-context","owner":"Code-Hex","description":"🦕【Deno】Propagate deadlines, a cancellation and other request-scoped values to multiple promise.","archived":false,"fork":false,"pushed_at":"2020-05-17T15:22:45.000Z","size":33,"stargazers_count":6,"open_issues_count":0,"forks_count":1,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-04-10T23:13:58.276Z","etag":null,"topics":["context","deno","golang","typescript"],"latest_commit_sha":null,"homepage":"https://blog.golang.org/context","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Code-Hex.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-05-16T08:33:19.000Z","updated_at":"2023-05-16T22:17:10.000Z","dependencies_parsed_at":"2022-11-01T17:30:53.335Z","dependency_job_id":null,"html_url":"https://github.com/Code-Hex/deno-context","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Code-Hex%2Fdeno-context","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Code-Hex%2Fdeno-context/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Code-Hex%2Fdeno-context/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Code-Hex%2Fdeno-context/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Code-Hex","download_url":"https://codeload.github.com/Code-Hex/deno-context/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248312135,"owners_count":21082638,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["context","deno","golang","typescript"],"created_at":"2024-08-03T03:01:28.537Z","updated_at":"2025-04-10T23:14:05.336Z","avatar_url":"https://github.com/Code-Hex.png","language":"TypeScript","readme":"# deno-context\n\n![.github/workflows/test.yml](https://github.com/Code-Hex/deno-context/workflows/.github/workflows/test.yml/badge.svg)\n\n🦕【Deno】Propagate deadlines, a cancellation and other request-scoped values to multiple promise. The behaviour is like Go's context.\n\n## Synopsis\n\nThis example passes a context with a timeout to tell a blocking methods that it should abandon its work after the timeout elapses.\n\n```typescript\nimport * as context from \"./context.ts\";\n\nconst tooSlow = (\n  ctx: context.Context,\n  ms: number,\n): Promise\u003cnumber\u003e =\u003e {\n  return new Promise\u003cnumber\u003e((resolve, reject) =\u003e {\n    const id = setTimeout((): void =\u003e {\n      clearTimeout(id);\n      resolve();\n    }, ms);\n    ctx.done()?.onCanceled((reason?: any) =\u003e {\n      clearTimeout(id);\n      reject(reason);\n    });\n    return ms;\n  });\n};\n\nconst ctx = new context.Background();\nconst tctx = new context.WithTimeout(ctx, 1000); // timeout by 1000ms\n\ntry {\n  await Promise.race([\n    tooSlow(tctx, 3000), // take 3s\n    tooSlow(tctx, 4000), // take 4s\n    tooSlow(tctx, 5000), // take 5s\n  ]);\n} catch (e) {\n  // Get this error by 1000ms.\n  // DeadlineExceeded: context deadline exceeded\n  console.warn(e);\n} finally {\n  tctx.cancel(); // To prevent leak.\n}\n```\n\n## About Context\n\nMost of the descriptions in here are copied and edited from the following links.\nhttps://golang.org/pkg/context\n\n\nThis library defines the Context type, which carries deadlines,\ncancellation signals, and other request-scoped values across API boundaries.\n\nThe WithCancel and WithTimeout functions take a\nContext (the parent) and return a derived Context (the child) and a cancel method.\nCalling the cancel method cancels the child and its children, removes the parent's\nreference to the child, and stops any associated timers. Failing to call the cancel\nmethod leaks the child and its children until the parent is canceled or the timer\nfires.\n\nPrograms that use Contexts should follow these rules to keep interfaces consistent across\nlibraries. Do not store Contexts inside any classes; instead, pass a Context explicitly to\neach function and method that needs it. The Context should be the first parameter,\ntypically named ctx:\n\n```typescript\n  function DoSomething(ctx: context.Context, arg Arg): context.ContextPromise\u003cvoid\u003e {\n    return new context.ContextPromise(ctx, (resolve, reject) =\u003e {\n      // ... use ctx ...\n    }\n  }\n\n  ... or\n\n  function DoSomething(ctx: context.Context, arg Arg): Promise\u003cvoid\u003e {\n    return new Promise((resolve, reject) =\u003e {\n      // ... use ctx ...\n    }\n  }\n```\n\n## context.Background\n\n```typescript\nconst ctx = new context.Background();\n```\n\nBackground returns a non-nil, empty Context. It is never canceled, has\nno values, and has no deadline. It is typically used by the main function,\ninitialization, and tests.\n\n## context.WithValue\n\n```typescript\nconst ctx = new context.Background();\nconst vctx = new context.WithValue(ctx, \"key\", \"value\");\n```\n\nWithValue returns a copy of parent in which the value associated with key is val.\n\nUse context Values only for request-scoped data that transits processes and APIs,\nnot for passing optional parameters to functions.\n\n\u003cdetails\u003e\n \u003csummary\u003eExample\u003c/summary\u003e\n\n```typescript\nconst ctx = new context.Background();\n\nconst key = \"language\";\nconst vctx = new context.WithValue(ctx, key, \"Deno\");\n\nconst f = (ctx: context.Context, key: string): void =\u003e {\n  const v = ctx.value(key);\n  if (v != undefined) {\n    console.log(\"found value:\", v);\n    return;\n  }\n  console.log(\"key not found:\", key);\n};\n\nf(vctx, key);\nf(vctx, \"color\");\n```\n\n\u003c/details\u003e\n\n## context.WithCancel\n\n```typescript\nconst ctx = new context.Background();\nconst cctx = new context.WithCancel(ctx);\n```\n\nWithCancel returns a copy of parent with a new done signal.\n\nThe returned context's done signal is signaled when the cancel method is called or\nwhen the parent context's done signal is signaled, whichever happens first.\n\n\u003cdetails\u003e\n \u003csummary\u003eExample\u003c/summary\u003e\n\n```typescript\nconst ctx = new context.Background();\nconst cctx = new context.WithCancel(ctx);\n\nconst canceler = async () =\u003e {\n  await tooSlow(cctx, 1000);\n  cctx.cancel();\n}\n\n// Run asynchronously\ncanceler();\n\ntry {\n  await Promise.race([\n    tooSlow(cctx, 3000),\n    tooSlow(cctx, 4000),\n    tooSlow(cctx, 5000),\n  ]);\n} catch (e) {\n  // Canceled: context canceled\n  console.warn(e);\n} finally {\n  cctx.cancel(); // To prevent leak.\n}\n```\n\n\u003c/details\u003e\n\n### Callback to be performed on cancel\n\nThe specified callback will be executed only once in the event that is emitted when the cancel method is called.\n  \nIf the cancel method has already been called, the passed callback will be executed immediately.\n\n\u003cdetails\u003e\n \u003csummary\u003eExample\u003c/summary\u003e\n\n```typescript\nimport * as context from \"./context.ts\";\n\nconst ctx = new context.Background();\nconst cctx = new context.WithCancel(ctx);\n\ncctx.done().onCanceled((reason?: any) =\u003e {\n  console.log(\"canceled reason:\", reason)\n})\n\nconsole.log(\"start cancel\")\ncctx.cancel();\nconsole.log(\"canceled\")\n```\n\n\u003c/details\u003e\n\n## context.WithTimeout\n\n```typescript\nconst ctx = new context.Background();\nconst tctx = new context.WithTimeout(ctx, 1000);\n```\n\nWithTimeout returns a copy of the parent context with the timeout\nadjusted to be no later than “ms\". If the parent's timeout is already\nearlier than “ms\", WithTimeout(parent, ms) is semantically equivalent\nto parent.\n\nThe returned context's done signal is signaled when the timeout expires,\nwhen the returned cancel method is called, or when the parent context's\ndone signal is signaled, whichever happens first.\n","funding_links":[],"categories":["基础设施","Modules"],"sub_categories":["JAM Stack/静态站点","Online Playgrounds","Utils","Assistants"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcode-hex%2Fdeno-context","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcode-hex%2Fdeno-context","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcode-hex%2Fdeno-context/lists"}