{"id":16823386,"url":"https://github.com/digitalbrainjs/c-promise","last_synced_at":"2025-03-17T04:31:19.342Z","repository":{"id":51389987,"uuid":"294195300","full_name":"DigitalBrainJS/c-promise","owner":"DigitalBrainJS","description":"Cancellable Promise with timeouts, AbortController, decorators, progress capturing, pause and user signals support","archived":false,"fork":false,"pushed_at":"2022-02-01T17:48:18.000Z","size":2907,"stargazers_count":41,"open_issues_count":1,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-27T17:36:29.596Z","etag":null,"topics":["abort","async","await","cancel","cancelable","cancellation","close","progress","promise","promises","signals"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","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/DigitalBrainJS.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-09-09T18:24:23.000Z","updated_at":"2024-10-24T04:47:22.000Z","dependencies_parsed_at":"2022-09-02T06:54:21.087Z","dependency_job_id":null,"html_url":"https://github.com/DigitalBrainJS/c-promise","commit_stats":null,"previous_names":[],"tags_count":75,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DigitalBrainJS%2Fc-promise","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DigitalBrainJS%2Fc-promise/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DigitalBrainJS%2Fc-promise/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DigitalBrainJS%2Fc-promise/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DigitalBrainJS","download_url":"https://codeload.github.com/DigitalBrainJS/c-promise/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243841210,"owners_count":20356443,"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":["abort","async","await","cancel","cancelable","cancellation","close","progress","promise","promises","signals"],"created_at":"2024-10-13T11:07:51.764Z","updated_at":"2025-03-17T04:31:18.988Z","avatar_url":"https://github.com/DigitalBrainJS.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Build Status](https://travis-ci.com/DigitalBrainJS/c-promise.svg?branch=master)](https://travis-ci.com/DigitalBrainJS/c-promise)\n[![Coverage Status](https://coveralls.io/repos/github/DigitalBrainJS/c-promise/badge.svg?branch=master)](https://coveralls.io/github/DigitalBrainJS/c-promise?branch=master)\n![npm](https://img.shields.io/npm/dm/c-promise2)\n![npm bundle size](https://img.shields.io/bundlephobia/minzip/c-promise2)\n![David](https://img.shields.io/david/DigitalBrainJS/c-promise)\n[![Stars](https://badgen.net/github/stars/DigitalBrainJS/c-promise)](https://github.com/DigitalBrainJS/c-promise/stargazers)\n\n## CPromise2\n\nThis lib provides `CPromise` class - an advanced version of the built-in Promise that supports:\n- deep cancellation **through rejection**. All static methods like `all`/`race`/`allSettled` support cancellation.\n- `all` \u0026 `allSettled` method support concurrency limitation and generators as promise producers\n- advanced progress capturing\n- flat async code writing using `generators/yield` as an alternative of `async/await`\n- event data flows (upstream \u0026 downstream)\n- `pause` \u0026 `resume` ability\n- timeouts\n- retries\n- `AbortController` support (providing \u0026 subscribing for multiple signals sources)\n- atomic subchains - such chains will be completed if the execution has been started, even if its upper chain received a Cancel signal.\n\n## Installation :hammer:\n\nnpm:\n```bash\n$ npm install c-promise2\n```\nyarn:\n```bash\n$ yarn add c-promise2\n```\nCDN:\n- [production UMD version](https://unpkg.com/c-promise2) \n(or [minified](https://unpkg.com/c-promise2/dist/c-promise.umd.min.js) ~11KB) - provides the CPromise class \nas the default export, other exports values declared as static properties\n\n- [production CommonJS version](https://unpkg.com/c-promise2/dist/c-promise.cjs.js)\n\n- [production ESM version](https://unpkg.com/c-promise2/dist/c-promise.mjs)\n\n### Quick start\n\n- Import CPromise class:\n\n````js\nimport { CPromise } from \"c-promise2\";\n````\n\n- Use `CPromise` constructor instead of `Promise`. To terminate internal async tasks (timers, request, streams etc.) gracefully subscribe your cleanup handler with `onCancel(handler)`:\n\n````js\nconst doTask = (ms)=\u003e{\n  return CPromise((resolve, reject, {onCancel})=\u003e{\n    const timer= setTimeout(resolve, ms, \"myValue\");\n    onCancel(()=\u003e clearTimeout(timer));\n  });\n}\n\nconst promise = doTask(1000).then(console.log);\n````\n\nOr/and turn generators to async functions with `CPromise.promisify` to write cancellable async code in flat style:\n````js\nconst doTask = CPromise.promisify(function*(ms){\n  yield CPromise.delay(ms);\n  return \"myValue\";\n});\n\nconst promise = doTask(1000).then(console.log);\n````\n- Call `promise.cancel([reason])` to cancel pending promise chain by rejecting the deepest\npending promise in the chain with a special `CanceledError` reason:\n````js\npromise.cancel(\"My bad\");\n````\n\n### Basic example\n\n#### Building plain CPromise chains using `then`\n[Codesandbox Live Demo](https://codesandbox.io/s/c-promise2-readme-basic1-7d8u0)\n````javascript\nimport { CPromise } from \"c-promise2\";\n\nconst promise= new CPromise((resolve, reject, {onCancel, onPause, onResume})=\u003e{\n    onCancel(()=\u003e{\n        //optionally some code here to abort your long-term task (abort request, stop timers etc.)\n    });\n}).then(\n    value =\u003e console.log(`Done: ${value}`), \n    (err, scope) =\u003e {\n        console.warn(`Failed: ${err}`); // Failed: CanceledError: canceled\n        console.log('chain isCanceled:', promise.isCanceled); // true\n        console.log('promise isCanceled:', scope.isCanceled); // true\n    }\n);\n\nconsole.log('isPromise:', promise instanceof Promise); // true\n\nsetTimeout(()=\u003e promise.cancel(), 1000);\n````\n\nLog:\n````\nisPromise: true\nFailed: CanceledError: canceled \nchain isCanceled: true\npromise isCanceled: true\n````\n\n#### Writing flat code using generators\n\n[Codesandbox Live Demo](https://codesandbox.io/s/cpromise-readme-flat-code1-forked-cg4ch?file=/src/index.js)\n\n````javascript\nimport { CPromise } from \"c-promise2\";\n\nconst sayHello = CPromise.promisify(function* (v) {\n  for (let i = 0; i \u003c 3; i++) {\n    console.log(`Hello [${i}]`);\n    yield CPromise.delay(1000);\n  }\n  return v + 1;\n});\n\nconst p = sayHello(5)\n  .then(function* (v) {\n    console.log(`Then`);\n    yield CPromise.delay(1000);\n    return v + 1;\n  })\n  .then((v) =\u003e console.log(`Done: ${v}`));\n\n// setTimeout(() =\u003e p.cancel(), 1000); stop trying\n````\n\n#### Abortable fetch with timeout\n\nThis is how an abortable fetch ([live example](https://jsfiddle.net/DigitalBrain/c6njyrt9/10/)) with a timeout might look like\n````javascript\nfunction fetchWithTimeout(url, {timeout, ...fetchOptions}= {}) {\n   return new CPromise((resolve, reject, {signal}) =\u003e {\n      fetch(url, {...fetchOptions, signal}).then(resolve, reject)\n   }, {timeout, nativeController: true})\n}\n\nconst promise= fetchWithTimeout('http://localhost/', {timeout: 5000})\n      .then(response =\u003e response.json())\n      .then(data =\u003e console.log(`Done: `, data), err =\u003e console.log(`Error: `, err))\n\nsetTimeout(()=\u003e promise.cancel(), 1000); \n\n// you able to call cancel() at any time to cancel the entire chain at any stage\n// the related network request will also be aborted\n````\n\n#### Note\n\nYou can use the [cp-fetch](https://www.npmjs.com/package/cp-fetch) which provides a ready to use \nCPromise wrapper for cross-platform fetch API, or [cp-axios](https://www.npmjs.com/package/cp-axios) wrapper for `axios` with powers of CPromise.\n\n## `.then` method behavior notes\n\nThe behavior of the method is slightly different from native Promise. \nIn the case when you cancel the chain after it has been resolved within one eventloop tick,\n`onRejected` will be called with a `CanceledError` instance, instead of `onFulfilled`.\nThis prevents the execution of unwanted code in the next eventloop tick if \nthe user canceled the promise immediately after the promise was resolved,\n during the same eventloop tick.\n\n## Ecosystem\n#### React\n* [use-async-effect2](https://www.npmjs.com/package/use-async-effect2) - feature-rich React async hooks that built on top of the cancellable promises ([CPromise](https://www.npmjs.com/package/c-promise2))\n\n#### Data fetching\n* [cp-axios](https://www.npmjs.com/package/cp-axios) - axios cancellable wrapper that supports CPromise context. Can be directly used in [use-async-effect2](https://www.npmjs.com/package/use-async-effect2) or general CPromise context\n* [cp-fetch](https://www.npmjs.com/package/cp-fetch) - cross-platform fetch wrapper that can be used in cooperation with [use-async-effect2](https://www.npmjs.com/package/use-async-effect2) or general [CPromise](https://www.npmjs.com/package/c-promise2) chains\n\n#### Backend\n* [cp-koa](https://www.npmjs.com/package/cp-koa) - a wrapper for [`koa`](https://www.npmjs.com/package/koa) that adds cancellable middlewares/routes to the framework\n\n## Learn more\n\nSee [CPromise wiki](https://github.com/DigitalBrainJS/c-promise/wiki)\n\n## API Reference\n\nJSDoc autogenerated [API Reference](https://github.com/DigitalBrainJS/c-promise/blob/master/API.md)\n\n## License\n\nThe MIT License Copyright (c) 2020 Dmitriy Mozgovoy robotshara@gmail.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\nPURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdigitalbrainjs%2Fc-promise","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdigitalbrainjs%2Fc-promise","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdigitalbrainjs%2Fc-promise/lists"}