{"name":"try","version":"0.3.5","author":{"name":"Szymon Wygnański","email":"s@finalclass.net"},"license":"MIT","_id":"try@0.3.5","maintainers":[{"name":"sel","email":"s@finalclass.net"}],"bugs":{"url":"https://github.com/finalclass/try.js/issues"},"dist":{"shasum":"feac0b17d6801a183acf9b473bbb8e7a38baf5ec","tarball":"http://registry-npm.ywwl.com/try/download/try-0.3.5.tgz","integrity":"sha512-YbrNYDXmQnPIbEAPfU42XrPIA7WKRfZtPrLFxp21Q5VZbB2krcexCm2Vh10Uubwlp+M8geZ2gX9c3ZDkmCel2g==","signatures":[{"sig":"MEUCIECP1Nx2W433vyJ7v5gybUqRXNOzwhij4InfP7Qi8emlAiEArqEwgnu+IEyGai0JGqxdkSFuLPHSo1kyF5z7nLBIN3k=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"size":2927,"noattachment":false,"key":"/try/-/try-0.3.5.tgz"},"main":"Try.js","_from":".","scripts":{"test":"jasmine-node spec/"},"_npmUser":{"name":"sel","email":"s@finalclass.net"},"repository":{"url":"git@github.com:finalclass/try.js.git","type":"git"},"_npmVersion":"1.3.2","description":"Async try / catch","directories":{},"dependencies":{},"devDependencies":{"jasmine-node":"~1.10.2"},"readme":"<p align=\"center\">\n   <b>Using this package?</b> Please consider <a href=\"https://github.com/arthurfiorette/try?sponsor=1\" target=\"_blank\">donating</a> to support the proposal ❤️\n  <br />\n  <sup>\n   Help <code>try</code> grow! Star and share this amazing repository with your friends and co-workers!\n  </sup>\n</p>\n\n<p align=\"center\">\n  <a title=\"MIT license\" target=\"_blank\" href=\"https://github.com/arthurfiorette/try/blob/main/LICENSE\"><img alt=\"License\" src=\"https://img.shields.io/github/license/arthurfiorette/try\"></a>\n  <a title=\"NPM Package\" target=\"_blank\" href=\"https://www.npmjs.com/package/try\"><img alt=\"Downloads\" src=\"https://img.shields.io/npm/dw/try?style=flat\"></a>\n  <a title=\"Bundle size\" target=\"_blank\" href=\"https://bundlephobia.com/package/try\"><img alt=\"Bundlephobia\" src=\"https://img.shields.io/bundlephobia/minzip/try/latest?style=flat\"></a>\n  <a title=\"Last Commit\" target=\"_blank\" href=\"https://github.com/arthurfiorette/try/commits/main\"><img alt=\"Last commit\" src=\"https://img.shields.io/github/last-commit/arthurfiorette/try\"></a>\n  <a title=\"Codecov\" target=\"_blank\" href=\"https://app.codecov.io/gh/arthurfiorette/try\"><img alt=\"Codecov\" src=\"https://codecov.io/gh/arthurfiorette/try/graph/badge.svg?token=ky185JbytA\"></a>\n  \n</p>\n\n<br />\n\n<h1>TRY</h1>\n\n> A [373-byte](https://bundlephobia.com/package/try) spec-compliant runtime-only implementation of the [`Result` class from the ECMAScript Try Operator proposal](https://github.com/arthurfiorette/proposal-try-operator).\n\n```ts\nimport { t } from 'try';\n\nconst [ok, error, value] = t(() => JSON.parse('{\"foo\": \"bar\"}'));\nconst [ok, error, value] = await t(axios.get('https://arthur.place'));\n```\n\n<br />\n\nThis package is a minimal and precise reference implementation of the [`Result` class](https://github.com/arthurfiorette/proposal-try-operator#result-class) as described in the [Try Operator](https://github.com/arthurfiorette/proposal-try-operator) proposal for JavaScript.\n\nIt aims to provide a lightweight and fast runtime utility that reflects exactly how the proposed `try` operator would behave, and **will not evolve independently of the proposal**.\n\nIf you'd like to suggest changes or improvements to the behavior or API, please [open an issue on the proposal repository](https://github.com/arthurfiorette/proposal-try-operator/issues/new/choose). Once discussed and approved there, changes will be reflected in this package.\n\n<br />\n\n- [Why This Exists](#why-this-exists)\n- [Usage](#usage)\n  - [Wrapping a Function Call](#wrapping-a-function-call)\n  - [`t()` alias](#t-alias)\n  - [Prefer Using the Result Object in Multi-Try Scenarios](#prefer-using-the-result-object-in-multi-try-scenarios)\n- [Works With Promises Too!](#works-with-promises-too)\n- [No `Result.bind`](#no-resultbind)\n- [Creating Results Manually](#creating-results-manually)\n- [Learn More](#learn-more)\n- [Acknowledgements](#acknowledgements)\n- [License](#license)\n\n<br />\n\n```ts\nimport { Result, ok, error, t } from 'try';\n\n// Synchronous function call\nconst [ok1, err1, val1] = t(JSON.parse, '{\"foo\":\"bar\"}');\n\n// Arrow function context\nconst [ok2, err2, val2] = t(() => decoder.decode(buffer));\n\n// Promise call\nconst [ok3, err3, val3] = await t(fetch, 'https://api.example.com');\n\n// Promise-safe call (safely catches both sync and async errors)\nconst [ok4, err4, val4] = await t(() => readFile('./config.json'));\n\n// Argument passthrough\nconst [ok5, err5, val5] = t((a, b) => a + b, 2, 3);\n\n// Keep full result object for readability\nconst result = await t(fetch, 'https://arthur.place');\nif (result.ok) console.log(await result.value.text());\n\n// Manual success and error results\nconst success = ok(42);\nconst failure = error(new Error('nope'));\n\n// Manual Result creation via class\nconst successObj = Result.ok('done');\nconst failureObj = Result.error('fail');\n```\n\n<br />\n\n## Why This Exists\n\nJavaScript error handling can be verbose and inconsistent. The [Try Operator proposal](https://github.com/arthurfiorette/proposal-try-operator) introduces a new pattern that returns structured `Result` objects instead of throwing exceptions, simplifying async and sync error flows alike.\n\nWhile the proposal is still in the works, this package provides a way to experiment with the new pattern in a standardized way.\n\nThis package provides a drop-in utility: `Result.try()` (or the shorter `t()`) to wrap expressions and handle errors in a clean, tuple-like form.\n\n```ts\nconst [ok, error, value] = t(JSON.parse, '{\"foo\":\"bar\"}');\n\nif (ok) {\n  console.log(value.foo);\n} else {\n  console.error('Invalid JSON', error);\n}\n```\n\n> You can destructure the result into `[ok, error, value]`, or access `.ok`, `.error`, and `.value` directly depending on your use case.\n\n<br />\n\n## Usage\n\nAll methods are documented via TSDoc, so your editor will guide you with full type support and autocomplete.\n\n### Wrapping a Function Call\n\nUse `Result.try()` or `t()` to wrap a potentially failing operation:\n\n```ts\nconst [ok, error, value] = Result.try(() => JSON.parse(request.body));\n\nif (ok) {\n  console.log(`Hello ${value.name}`);\n} else {\n  console.error(`Invalid JSON!`);\n}\n```\n\n> [!NOTE]  \n>  `Result.try(() => fn())` is verbose compared to the proposal's future `try fn()` syntax. Always prefer to use the `t()` alias for cleaner code.\n\n<br />\n\n### `t()` alias\n\nTo make code cleaner and more ergonomic while we wait for language-level syntax sugar, this package also exports `t`, a shortcut for `Result.try`.\n\n```ts\nimport { readFile } from 'node:fs/promises';\nimport { readFileSync } from 'node:fs';\n\n// Example (this is void)\nconst [ok, error, value] = t(readFileSync, './config.json');\n// If `this` matters in your context\nconst [ok, error, value] = t(() => decoder.decode(request.body));\n// Promises don't need wrapping\nconst [ok, error, value] = await t(axios.get('http://example.com'));\n// Safer way even for promises (catches sync errors before returning a promise)\nconst [ok, error, value] = await t(readFile, path);\n```\n\nThe `t(fn, ...args)` form is ideal: it automatically passes arguments to your function, preserves full TypeScript inference, and keeps code short and readable.\n\n```ts\nfunction divide(a: number, b: number) {\n  return a / b;\n}\n\nconst [ok, error, value] = t(divide, 10, 2);\n// ok: true, value: 5\n```\n\n<br />\n\n### Prefer Using the Result Object in Multi-Try Scenarios\n\nWhile destructuring works well for simple use cases, it can lead to awkward variable naming and clutter when handling multiple `try` results. In these cases, **it's recommended to keep the full result object and access `.ok`, `.error`, and `.value` directly** for better clarity and readability.\n\n❌ Bad (managing variable names becomes cumbersome):\n\n```ts\n// error handling omitted for brevity\nconst [ok1, error1, value1] = Result.try(() => axios.get(...));\nconst [ok2, error2, value2] = Result.try(() => value1.data.property);\n```\n\n✅ Better (clearer structure and easier to follow):\n\n```ts\n// error handling omitted for brevity\nconst response = await Result.try(fetch('https://arthur.place'));\nconst data = await Result.try(() => response.value.text()));\n```\n\nUsing the result object directly avoids unnecessary boilerplate and naming inconsistencies, especially in nested or sequential operations. It's a cleaner, more scalable pattern that mirrors real-world error handling flows.\n\n<br />\n\n## Works With Promises Too!\n\nYou can pass a `Promise` directly and get a `Result`-wrapped version:\n\n```ts\nconst [ok, error, value] = await t(\n  fs.promises.readFile('./config.json')\n);\n\nif (ok) {\n  const config = JSON.parse(value.toString());\n} else {\n  console.error('Failed to read file', error);\n}\n```\n\nThe return value of `t()` is automatically `await`-able if the function returns a promise, no extra handling required.\n\n<br />\n\n## No `Result.bind`\n\nThis implementation **will never provide a `Result.bind()`** (like `util.promisify`) because the Try Operator follows the [Caller’s Approach](https://github.com/arthurfiorette/proposal-try-operator/tree/main#callers-approach) model.\n\nThat means **error handling belongs to the calling context**, not the function itself. Wrapping a function with `bind()` would push error encapsulation into the callee, breaking that principle.\n\n**In short:** the caller chooses to wrap a function call in `Result.try`, not the function author.\n\n<br />\n\n## Creating Results Manually\n\nYou can also create `Result` objects directly:\n\n```ts\nimport { Result, ok, error } from 'try';\n\n// With full Result class\nconst res1 = Result.ok('done');\nconst res2 = Result.error('fail');\n\n// Shorthand\nconst okRes = ok(42);\nconst errRes = error('oops');\n```\n\nThis is useful when bridging non-try-based code or mocking results.\n\n<br />\n\n## Learn More\n\nTo learn about the underlying proposal, including syntax goals and motivation, visit:\n\n🔗 https://github.com/arthurfiorette/proposal-try-operator\n\n<br />\n\n## Acknowledgements\n\nMany thanks to [Szymon Wygnański](https://finalclass.net) for transferring the `try` package name on NPM to this project. Versions below `1.0.0` served a different purpose, but with his permission, the project was repurposed to host an implementation of the proposal’s `Result` class.\n\n<br />\n\n## License\n\nBoth the project and the proposal are licensed under the [MIT](./LICENSE) license.\n\n<br />\n","publish_time":1374684477894,"_cnpm_publish_time":1374684477894,"dist-tags":{"latest":"1.0.3"}}