{"id":18552437,"url":"https://github.com/andrejewski/tactic","last_synced_at":"2025-05-15T11:13:12.858Z","repository":{"id":65513996,"uuid":"74592597","full_name":"andrejewski/tactic","owner":"andrejewski","description":"Promise utilities for just the worst people","archived":false,"fork":false,"pushed_at":"2017-07-29T12:42:31.000Z","size":51,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-01-26T12:04:05.804Z","etag":null,"topics":["javascript","promise"],"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/andrejewski.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":"2016-11-23T16:04:32.000Z","updated_at":"2024-06-06T12:54:16.000Z","dependencies_parsed_at":"2023-01-26T21:00:59.009Z","dependency_job_id":null,"html_url":"https://github.com/andrejewski/tactic","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrejewski%2Ftactic","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrejewski%2Ftactic/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrejewski%2Ftactic/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrejewski%2Ftactic/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/andrejewski","download_url":"https://codeload.github.com/andrejewski/tactic/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239278507,"owners_count":19612329,"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":["javascript","promise"],"created_at":"2024-11-06T21:14:13.344Z","updated_at":"2025-02-17T10:43:33.756Z","avatar_url":"https://github.com/andrejewski.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Tactic\nPromise utilities for just the worst people\n\nTactic is a library of Promise primitives we have written ourselves plenty of times, but this is the last time we reinvent the wheel.\nTactic is Promise library independent.\n\n```sh\nnpm install tactic\n```\n\n## What's in the box!?\nTactic includes these Promise abstractions/helpers:\n\n- Defer\n- Cancel, a defer with a `cancel()` method\n- Timeout, a promise using `setTimeout()`\n- Domain\n\nDomain is one I made up, but it captures an ad-hoc pattern I see very frequently.\n\n### Defer\nDefers are sometimes labeled an anti-pattern but they are pretty useful when it comes down to building something and much more flexible than Promises (which is the main concern).\n\nDefers are just Promises that you can resolve and reject outside of the scope of the function usually passed to the Promise constructor. Check out `src/defer.js`, it really is that simple.\n\n```js\n// Defers are great with async/await\n// Here we don't need to check if we are connected\nconst database = null // your db\nconst Defer = require('tactic').Defer\nconst dbConnected = new Defer()\n\ndatabase.connect(error =\u003e {\n  error ? dbConnected.reject(error) : dbConnected.resolve()\n})\n\nasync function query (id) {\n  // Just await being connected\n  // If we are already we go straight to querying\n  await dbConnected\n  database.query(id)\n}\n\nquery('yo mama')\n```\n\n### Cancel\nCancel really is only included to stop bike shedding. Here we say a cancellation is a rejection with a `CancelError`, which can be checked with `isCancelError(reason)`. Those are the rules. I didn't make them. I just thought them up and wrote them down.\n\nAny promise can be wrapped with a Cancel using the `cancellable(promise)` function and then be cancelled by calling `cancel()` on the result.\n\n```js\nconst {\n  cancellable,\n  isCancelError\n} = require('tactic')\nconst assert = require('assert')\nconst fetch = null // whatever you use for api calls\n\nconst apiCall = cancellable(fetch('/api/my-whatever'))\n\n// somewhere before it resolves\napiCall.cancel()\n\napiCall.catch(reason =\u003e {\n  assert(isCancelError(reason))\n})\n```\n\n### Timeout\nAgain, anyone could write a Timeout promise. The problem is we all have. Here we say a timeout is a rejection with a `TimeoutError`, which can be checked with `isTimeoutError(x)`. (Consistency!)\n\nAny promise can be wrapped in a Timeout using the `timeout(promise, milliseconds)` function.\n\n```js\nconst {\n  timeout,\n  isTimeoutError\n} = require('tactic')\nconst assert = require('assert')\nconst fetch = null // whatever you use for api calls\n\nconst threeSeconds = 3000\nconst apiCall = timeout(fetch('/api/my-whatever'), threeSeconds)\n\n// if the api call does not resolve in 3 seconds\napiCall.catch(reason =\u003e {\n  assert(isTimeoutError(reason))\n})\n```\n\n### Domain\nOkay, so this is new. A domain is just a slot where only one promise can be run at a given time to prevent race conditions and clobbering. The poster child for this problem is real-time search, that instant results-as-you-type deal. As someone is typing they fire off \"cow\" and then \"coward\", each with an network call. In the case where \"coward\" resolves first (latency or just less results so faster), the \"cow\" result will overwrite its results when it returns.\n\nDomains solve this by cancelling promises that happen at the same time, leaving all but one. And there are two Domain variants: `TakeDomain` and `DropDomain`. With TakeDomain the newest promise takes the slot from any other promise already running, and that old promise is cancelled (\"coward\" wins). With DropDomain the newest promise, if there is another already in the domain, is dropped i.e. cancelled (\"cow\" wins).\n\nBoth domains accept competing promises via `run()` which accepts a function which returns a Cancel. Note that you must pass a Cancel, so any plain Promise needs to be wrapped with `cancellable(promise)` (no magic casting here).\n\n```js\nconst {\n  cancellable,\n  DropDomain\n} = require('tactic')\nconst fetch = null // whatever you use for api calls\n\nconst domain = new DropDomain()\nconst result = domain.run(function firstCall () {\n  const apiCall = fetch('/api/my-search')\n  return cancellable(apiCall)\n})\n\n// if firstCall has not completed\n// secondCall won't ever be called\nconst promise = domain.run(function secondCall () {\n  const apiCall = fetch('/api/my-search')\n  return cancellable(apiCall)\n})\n\n// firstCall will resolve with whatever in result\n// promise will have rejected with a CancelError\n```\n\n### Recap\nHere are all the things Tactic exposes:\n\n- `class Defer`\n  - `.resolve()`\n  - `.reject()`\n  - `.then()`, `.catch()`, and `.finally()` (if your base Promise supports it)\n- `cancellable(promise) Cancel`\n  - `.cancel([message])`\n- `isCancelError(any) boolean`\n- `timeout(promise, milliseconds[, message])`\n- `isTimeoutError(any) boolean`\n- `class TakeDomain`\n- `class DropDomain`\n\nThe `[message]` bits are for optionally setting the error message.\n\nNote: you can access the classes Cancel, CancelError, Timeout, and TimeoutError directly from their respective `tactic/lib/{cancel|timeout}` modules. But you shouldn't so I make you feel bad about it.\n\n## Contributing\nContributions are incredibly welcome as long as they are standardly applicable and pass the tests (or break bad ones). Tests are written in AVA.\n\n```bash\n# running tests\nnpm run test\n```\n\nFollow me on [Twitter](https://twitter.com/compooter) for updates or just for the lolz and please check out my other [repositories](https://github.com/andrejewski) if I have earned it. I thank you for reading.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrejewski%2Ftactic","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandrejewski%2Ftactic","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrejewski%2Ftactic/lists"}