├── .nvmrc ├── .prettierignore ├── CNAME ├── docs ├── .nojekyll ├── CNAME ├── logo.webp ├── example.png ├── example.webp ├── favicon.ico ├── images │ └── of.png ├── logo_x1.png ├── logo_x2.png ├── icons │ ├── apple-icon.png │ ├── favicon-16x16.png │ ├── favicon-32x32.png │ ├── favicon-96x96.png │ ├── ms-icon-70x70.png │ ├── ms-icon-144x144.png │ ├── ms-icon-150x150.png │ ├── ms-icon-310x310.png │ ├── android-icon-36x36.png │ ├── android-icon-48x48.png │ ├── android-icon-72x72.png │ ├── android-icon-96x96.png │ ├── apple-icon-114x114.png │ ├── apple-icon-120x120.png │ ├── apple-icon-144x144.png │ ├── apple-icon-152x152.png │ ├── apple-icon-180x180.png │ ├── apple-icon-57x57.png │ ├── apple-icon-60x60.png │ ├── apple-icon-72x72.png │ ├── apple-icon-76x76.png │ ├── android-icon-144x144.png │ ├── android-icon-192x192.png │ └── apple-icon-precomposed.png ├── more.md ├── browserconfig.xml ├── _sidebar.md ├── configuration.md ├── results.md ├── default_value.md ├── overwrite_error.md ├── manifest.json ├── usage.md ├── retry.md ├── installation.md ├── timeout.md ├── callable_types.md ├── how-to.md ├── README.md ├── about.md ├── functions.md ├── sw.js ├── changelog.md └── index.html ├── _config.yml ├── .eslintignore ├── .github └── FUNDING.yml ├── .ignore ├── .npmrc ├── src ├── const │ ├── error.js │ └── type.js ├── util │ └── isFunction.js ├── core │ ├── ofResult.js │ ├── ofOutcome.js │ ├── of.js │ ├── ofError.js │ ├── ofIt.js │ ├── ofSync.js │ ├── ofCase.js │ ├── ofAny.js │ └── ofAnyCase.js ├── index.mjs └── class │ └── Of.js ├── .dcignore ├── .mailmap ├── renovate.json ├── rollup.config.mjs ├── .gitattributes ├── .travis.yml ├── .codeclimate.yml ├── .editorconfig ├── .babelrc ├── .sonarcloud.properties ├── .prettierrc ├── .npmignore ├── .remarkrc ├── .gitignore ├── .eslintrc.json ├── LICENSE.md ├── _layouts └── default.html ├── package.json ├── README.md ├── BADGES.md ├── CODE_OF_CONDUCT.md ├── dist ├── of.mjs ├── of.cjs ├── of.js ├── of.d.ts ├── of.js.map ├── of.cjs.map └── of.mjs.map └── test └── index.test.js /.nvmrc: -------------------------------------------------------------------------------- 1 | lts/* -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /CNAME: -------------------------------------------------------------------------------- 1 | of.js.org -------------------------------------------------------------------------------- /docs/.nojekyll: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/CNAME: -------------------------------------------------------------------------------- 1 | of.js.org -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-tactile 2 | title: null 3 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | /dist/ 2 | /docs/ 3 | /test/ 4 | node_modules/** 5 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | ko_fi: r37r0m0d3l 2 | open_collective: r37r0m0d3l -------------------------------------------------------------------------------- /.ignore: -------------------------------------------------------------------------------- 1 | .idea 2 | /node_modules 3 | /temp 4 | package-lock.json 5 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | engine-strict = true 2 | save = true 3 | save-exact = true -------------------------------------------------------------------------------- /src/const/error.js: -------------------------------------------------------------------------------- 1 | export const ERR_UNKNOWN = "Unknown Error"; 2 | -------------------------------------------------------------------------------- /.dcignore: -------------------------------------------------------------------------------- 1 | .github/** 2 | _layouts/** 3 | dist/** 4 | docs/** 5 | test/** -------------------------------------------------------------------------------- /.mailmap: -------------------------------------------------------------------------------- 1 | r37r0m0d3l # Anton Trofimenko 2 | -------------------------------------------------------------------------------- /docs/logo.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/logo.webp -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /docs/example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/example.png -------------------------------------------------------------------------------- /docs/example.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/example.webp -------------------------------------------------------------------------------- /docs/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/favicon.ico -------------------------------------------------------------------------------- /docs/images/of.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/images/of.png -------------------------------------------------------------------------------- /docs/logo_x1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/logo_x1.png -------------------------------------------------------------------------------- /docs/logo_x2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/logo_x2.png -------------------------------------------------------------------------------- /docs/icons/apple-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/apple-icon.png -------------------------------------------------------------------------------- /docs/icons/favicon-16x16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/favicon-16x16.png -------------------------------------------------------------------------------- /docs/icons/favicon-32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/favicon-32x32.png -------------------------------------------------------------------------------- /docs/icons/favicon-96x96.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/favicon-96x96.png -------------------------------------------------------------------------------- /docs/icons/ms-icon-70x70.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/ms-icon-70x70.png -------------------------------------------------------------------------------- /docs/icons/ms-icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/ms-icon-144x144.png -------------------------------------------------------------------------------- /docs/icons/ms-icon-150x150.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/ms-icon-150x150.png -------------------------------------------------------------------------------- /docs/icons/ms-icon-310x310.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/ms-icon-310x310.png -------------------------------------------------------------------------------- /docs/icons/android-icon-36x36.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/android-icon-36x36.png -------------------------------------------------------------------------------- /docs/icons/android-icon-48x48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/android-icon-48x48.png -------------------------------------------------------------------------------- /docs/icons/android-icon-72x72.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/android-icon-72x72.png -------------------------------------------------------------------------------- /docs/icons/android-icon-96x96.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/android-icon-96x96.png -------------------------------------------------------------------------------- /docs/icons/apple-icon-114x114.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/apple-icon-114x114.png -------------------------------------------------------------------------------- /docs/icons/apple-icon-120x120.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/apple-icon-120x120.png -------------------------------------------------------------------------------- /docs/icons/apple-icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/apple-icon-144x144.png -------------------------------------------------------------------------------- /docs/icons/apple-icon-152x152.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/apple-icon-152x152.png -------------------------------------------------------------------------------- /docs/icons/apple-icon-180x180.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/apple-icon-180x180.png -------------------------------------------------------------------------------- /docs/icons/apple-icon-57x57.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/apple-icon-57x57.png -------------------------------------------------------------------------------- /docs/icons/apple-icon-60x60.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/apple-icon-60x60.png -------------------------------------------------------------------------------- /docs/icons/apple-icon-72x72.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/apple-icon-72x72.png -------------------------------------------------------------------------------- /docs/icons/apple-icon-76x76.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/apple-icon-76x76.png -------------------------------------------------------------------------------- /docs/icons/android-icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/android-icon-144x144.png -------------------------------------------------------------------------------- /docs/icons/android-icon-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/android-icon-192x192.png -------------------------------------------------------------------------------- /docs/icons/apple-icon-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/await-of/of/HEAD/docs/icons/apple-icon-precomposed.png -------------------------------------------------------------------------------- /rollup.config.mjs: -------------------------------------------------------------------------------- 1 | /* eslint-env node */ 2 | import rollupConfigPkg from "@r37r0m0d3l/rollup-config-pkg"; 3 | 4 | export default rollupConfigPkg("of", "of"); 5 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text eol=lf 3 | *.txt lf 4 | *.md lf 5 | *.jpg binary 6 | *.jpeg binary 7 | *.gif binary 8 | *.png binary 9 | *.webp binary 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | before_install: 3 | - "npm install npm -g" 4 | node_js: 5 | - "12.16.3" 6 | npm: 7 | - "6.13.4" 8 | env: 9 | - TEST_SUITE=test 10 | script: 11 | - npm run $TEST_SUITE -------------------------------------------------------------------------------- /.codeclimate.yml: -------------------------------------------------------------------------------- 1 | plugins: 2 | eslint: 3 | channel: eslint-6 4 | config: 5 | config: .eslintrc.json 6 | extensions: 7 | - .js 8 | ignore_warnings: true 9 | enabled: true 10 | -------------------------------------------------------------------------------- /src/const/type.js: -------------------------------------------------------------------------------- 1 | export const FUNC = "Function"; 2 | export const FUNC_ASYNC = "AsyncFunction"; 3 | export const FUNC_GEN = "GeneratorFunction"; 4 | export const OBJ_GEN = "[object Generator]"; 5 | export const PROMISE = "Promise"; 6 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_size = 2 7 | indent_style = space 8 | insert_final_newline = false 9 | trim_trailing_whitespace = true 10 | tab_width = 2 11 | 12 | [*.js] 13 | max_line_length = 120 14 | -------------------------------------------------------------------------------- /src/util/isFunction.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {*} value 3 | * @returns {boolean} 4 | */ 5 | export function isFunction(value) { 6 | if (Object.prototype.toString.call(value) !== "[object Function]") { 7 | return false; 8 | } 9 | return !/^class\s/.test(Function.prototype.toString.call(value)); 10 | } 11 | -------------------------------------------------------------------------------- /src/core/ofResult.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @name ofResult 3 | * @param {Promise} promise 4 | * @param {*=} defaultResult 5 | * @returns {Promise<*>} 6 | */ 7 | export function ofResult(promise, defaultResult) { 8 | return Promise.resolve(promise) 9 | .then((result) => result) 10 | .catch(() => defaultResult); 11 | } 12 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "exclude": "node_modules/**", 3 | "presets": [ 4 | [ 5 | "@babel/preset-env", 6 | { 7 | "targets": { 8 | "node": true 9 | } 10 | } 11 | ] 12 | ], 13 | "plugins": ["@babel/plugin-proposal-class-properties", "@babel/plugin-proposal-private-methods"] 14 | } 15 | -------------------------------------------------------------------------------- /.sonarcloud.properties: -------------------------------------------------------------------------------- 1 | # Path to sources 2 | sonar.sources=./src/ 3 | sonar.exclusions=./_layouts 4 | #sonar.inclusions= 5 | 6 | # Path to tests 7 | #sonar.tests= 8 | #sonar.test.exclusions= 9 | #sonar.test.inclusions= 10 | 11 | # Source encoding 12 | sonar.sourceEncoding=UTF-8 13 | 14 | # Exclusions for copy-paste detection 15 | sonar.cpd.exclusions=./dist/*.* 16 | -------------------------------------------------------------------------------- /docs/more.md: -------------------------------------------------------------------------------- 1 | # 👀 Discover more 2 | 3 | --- 4 | 5 | [My other projects](https://r37r0m0d3l.icu/open_source_map) 6 | 7 | 8 | 9 | --- 10 | -------------------------------------------------------------------------------- /docs/browserconfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | #ffffff 9 | 10 | 11 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "always", 3 | "bracketSpacing": true, 4 | "endOfLine": "lf", 5 | "htmlWhitespaceSensitivity": "strict", 6 | "jsxBracketSameLine": false, 7 | "jsxSingleQuote": false, 8 | "printWidth": 120, 9 | "quoteProps": "consistent", 10 | "semi": true, 11 | "singleQuote": false, 12 | "tabWidth": 2, 13 | "trailingComma": "all", 14 | "useTabs": false 15 | } -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | /.babelrc 2 | /.editorconfig 3 | /.eslintignore 4 | /.eslintrc.json 5 | /.gitattributes 6 | /.gitignore 7 | /.idea 8 | /.ignore 9 | /.mailmap 10 | /.npmignore 11 | /.npmrc 12 | /.nvmrc 13 | /.prettierignore 14 | /.prettierrc 15 | /.remarkrc 16 | /.sonarcloud.properties 17 | /.travis.yml 18 | /.yarnrc 19 | /CHANGELOG.md 20 | /CNAME 21 | /README.md 22 | /_config.yml 23 | /_layouts/ 24 | /docs/ 25 | /package-lock.json 26 | /renovate.json 27 | /src/ 28 | /temp/ 29 | /test/ 30 | /yarn.lock 31 | -------------------------------------------------------------------------------- /src/core/ofOutcome.js: -------------------------------------------------------------------------------- 1 | import { ofAnyCase } from "./ofAnyCase.js"; 2 | 3 | /** 4 | * @name ofOutcome 5 | * @description Returns result or thrown error wherever happens 6 | * @param {Function|Promise} callable 7 | * @param {*=} config 8 | * @returns {Promise<*>} 9 | */ 10 | export function ofOutcome(callable, config = {}) { 11 | return new Promise((resolve) => 12 | ofAnyCase(callable, config).then(([result, error]) => { 13 | resolve(error ? error : result); 14 | }), 15 | ); 16 | } 17 | -------------------------------------------------------------------------------- /.remarkrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "remark-preset-lint-consistent", 4 | "remark-preset-lint-markdown-style-guide", 5 | "remark-preset-lint-recommended", 6 | [ 7 | "lint-no-file-name-irregular-characters", 8 | false 9 | ], 10 | [ 11 | "remark-lint-maximum-line-length", 12 | 180 13 | ], 14 | [ 15 | "remark-lint-list-item-spacing", 16 | false 17 | ], 18 | [ 19 | "remark-lint-table-pipe-alignment", 20 | false 21 | ] 22 | ] 23 | } -------------------------------------------------------------------------------- /src/core/of.js: -------------------------------------------------------------------------------- 1 | import { ERR_UNKNOWN } from "../const/error.js"; 2 | 3 | /** 4 | * @name of 5 | * @param {Promise} promise 6 | * @returns {Promise<[*, unknown] | [undefined, *]>} 7 | */ 8 | export function of(promise) { 9 | return Promise.resolve(promise) 10 | .then((result) => [result]) 11 | .catch((caughtError) => { 12 | if (caughtError === undefined || caughtError === null) { 13 | caughtError = new Error(ERR_UNKNOWN); 14 | } 15 | return [undefined, caughtError]; 16 | }); 17 | } 18 | -------------------------------------------------------------------------------- /src/index.mjs: -------------------------------------------------------------------------------- 1 | import { Of } from "./class/Of.js"; 2 | import { of } from "./core/of.js"; 3 | import { ofAny } from "./core/ofAny.js"; 4 | import { ofAnyCase } from "./core/ofAnyCase.js"; 5 | import { ofCase } from "./core/ofCase.js"; 6 | import { ofError } from "./core/ofError.js"; 7 | import { ofIt } from "./core/ofIt.js"; 8 | import { ofOutcome } from "./core/ofOutcome.js"; 9 | import { ofResult } from "./core/ofResult.js"; 10 | import { ofSync } from "./core/ofSync.js"; 11 | 12 | export { Of, of, ofAny, ofAnyCase, ofCase, ofError, ofIt, ofOutcome, ofResult, ofSync }; 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /node_modules 3 | 4 | # Logs 5 | logs 6 | *.log 7 | npm-debug.log* 8 | yarn-debug.log* 9 | yarn-error.log* 10 | lerna-debug.log* 11 | 12 | # OS 13 | .DS_Store 14 | 15 | # Tests 16 | /coverage 17 | /.nyc_output 18 | 19 | # IDEs and editors 20 | /.idea 21 | .project 22 | .classpath 23 | .c9/ 24 | *.launch 25 | .settings/ 26 | *.sublime-workspace 27 | 28 | # IDE - VSCode 29 | .vscode/* 30 | !.vscode/settings.json 31 | !.vscode/tasks.json 32 | !.vscode/launch.json 33 | !.vscode/extensions.json 34 | /.env 35 | /.docker/ 36 | 37 | /temp 38 | /package-lock.json 39 | /yarn.lock 40 | -------------------------------------------------------------------------------- /docs/_sidebar.md: -------------------------------------------------------------------------------- 1 | - 🚀 Getting Started 2 | - [🤔 About](about.md) 3 | - [💾 Installation](installation.md) 4 | - 🏗 API 5 | - [💬 Usage](usage.md) 6 | - [⚙️ Configuration](configuration.md) 7 | - [💡️ Functions](functions.md) 8 | - [📚 How-to](how-to.md) 9 | - 🤷‍♂️ Examples 10 | - [🔰 Callable Types](callable_types.md) 11 | - [✅ Results](results.md) 12 | - [💔 Overwrite Error](overwrite_error.md) 13 | - [🔨 Default Value](default_value.md) 14 | - [🔄️ Retry](retry.md) 15 | - [⏲️ Timeout](timeout.md) 16 | - [🆕 Changelog](changelog.md) 17 | - [👀 More](more.md) 18 | -------------------------------------------------------------------------------- /src/core/ofError.js: -------------------------------------------------------------------------------- 1 | import { ERR_UNKNOWN } from "../const/error.js"; 2 | 3 | /** 4 | * @name ofError 5 | * @param {Promise} promise 6 | * @param {*=} overrideError 7 | * @returns {Promise<*>} 8 | */ 9 | export function ofError(promise, overrideError) { 10 | return Promise.resolve(promise) 11 | .then(() => undefined) 12 | .catch((caughtError) => { 13 | if (caughtError === undefined || caughtError === null) { 14 | caughtError = new Error(ERR_UNKNOWN); 15 | } 16 | if (overrideError instanceof Error) { 17 | caughtError = overrideError; 18 | } else if (typeof overrideError === "string") { 19 | caughtError.message = overrideError; 20 | } 21 | return caughtError; 22 | }); 23 | } 24 | -------------------------------------------------------------------------------- /src/core/ofIt.js: -------------------------------------------------------------------------------- 1 | import { ERR_UNKNOWN } from "../const/error.js"; 2 | 3 | /** 4 | * @name ofIt 5 | * @param {Promise} promise 6 | * @param {*=} defaultResult 7 | * @param {*=} overrideError 8 | * @returns {Promise<[*, unknown] | [undefined, *]>} 9 | */ 10 | export function ofIt(promise, defaultResult, overrideError) { 11 | return Promise.resolve(promise) 12 | .then((result) => [result]) 13 | .catch((caughtError) => { 14 | if (caughtError === undefined || caughtError === null) { 15 | caughtError = new Error(ERR_UNKNOWN); 16 | } 17 | if (overrideError instanceof Error) { 18 | caughtError = overrideError; 19 | } else if (typeof overrideError === "string") { 20 | caughtError.message = overrideError; 21 | } 22 | return [defaultResult, caughtError]; 23 | }); 24 | } 25 | -------------------------------------------------------------------------------- /docs/configuration.md: -------------------------------------------------------------------------------- 1 | # ⚙️ Configuration 2 | 3 | --- 4 | 5 | Example configuration. 6 | 7 | ```javascript 8 | const configuration = { 9 | // Array of arguments that will be used in function call. 10 | args: [{x: 1, y: 2}, true], 11 | // Default value in case of error. Will replace undefined result. 12 | defaults: "Default Value", 13 | // Custom error, replaces thrown error. 14 | error: new Error("Whoops"), 15 | // Count of additional retries after failed execution. 16 | // Not usable with promises use function with arguments instead. 17 | retries: 3, 18 | // Milliseconds for the execution timeout. 19 | timeout: 1000, 20 | }; 21 | const [result, error] = await ofAnyCase(async () => {}, configuration); 22 | ``` 23 | 24 | TypeScript interface. 25 | 26 | ```typescript 27 | export interface IOfConfig { 28 | args?: any[]; 29 | defaults?: any; 30 | error?: string | Error; 31 | retries?: number; 32 | timeout?: number; 33 | } 34 | ``` 35 | 36 | --- 37 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "commonjs": true, 4 | "es6": true, 5 | "node": true 6 | }, 7 | "extends": ["plugin:prettier/recommended", "eslint:recommended"], 8 | "globals": { 9 | "Atomics": "readonly", 10 | "SharedArrayBuffer": "readonly" 11 | }, 12 | "parser": "babel-eslint", 13 | "parserOptions": { 14 | "allowImportExportEverywhere": true, 15 | "ecmaVersion": 2018, 16 | "sourceType": "module" 17 | }, 18 | "plugins": ["prettier"], 19 | "rules": { 20 | "eqeqeq": ["error", "always"], 21 | "id-length": ["error", { "exceptions": ["x", "y", "z"], "min": 2, "properties": "never" }], 22 | "linebreak-style": ["error", "unix"], 23 | "no-console": "warn", 24 | "no-implicit-coercion": "error", 25 | "no-multi-assign": "error", 26 | "no-param-reassign": "off", 27 | "no-ternary": "off", 28 | "prettier/prettier": "error", 29 | "quotes": ["error", "double", { "allowTemplateLiterals": true, "avoidEscape": true }], 30 | "semi": ["error", "always"], 31 | "yoda": "error" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /docs/results.md: -------------------------------------------------------------------------------- 1 | # ✅ Results 2 | 3 | --- 4 | 5 | This is a basic usage of the library. Whatever happens, this will swallow error. 6 | 7 | ```javascript 8 | const promise = new Promise((resolve, _reject) => { 9 | resolve({ data: true }); 10 | }); 11 | 12 | const [result, error] = await ofAnyCase(promise); 13 | 14 | console.log(result); // { data: true } 15 | console.warn(error); // no error thrown, so it's undefined 16 | ``` 17 | 18 | You can skip the error value. 19 | 20 | ```javascript 21 | async function doSomething() { 22 | return true; 23 | } 24 | 25 | const [result] = await ofAnyCase(doSomething); 26 | 27 | console.log(result); // true 28 | ``` 29 | 30 | ?> You can use `ofResult()` or `Of.result()` to optimize execution 31 | 32 | --- 33 | 34 | Or you can skip result value if the function has no result value but can throw an error. 35 | 36 | ```javascript 37 | async function doSomething() { 38 | throw "Some error"; 39 | } 40 | 41 | const [, error] = await ofAnyCase(doSomething); 42 | 43 | if (error) { 44 | // Yes, here we know that something wrong happened 45 | } 46 | ``` 47 | 48 | --- 49 | -------------------------------------------------------------------------------- /docs/default_value.md: -------------------------------------------------------------------------------- 1 | # 🔨 Default Value 2 | 3 | --- 4 | 5 | In case of error, you can overwrite result value. In the example you don't care about the error, just need to know that something went wrong. 6 | 7 | ```javascript 8 | async function doSomething() { 9 | throw "Any kind of error"; 10 | } 11 | 12 | const config = { 13 | defaults: null, 14 | }; 15 | 16 | const [result, error] = await ofAnyCase(doSomething(), config); 17 | console.log(result); // null 18 | console.warn(error); // "Any kind of error" 19 | ``` 20 | 21 | ?> You can use `ofIt()` or `Of.it()` to optimize execution 22 | 23 | --- 24 | 25 | You must note that in case of successful completion value from configuration don't overwrite result if it's undefined. 26 | 27 | ```javascript 28 | async function returnsVoid() { 29 | return undefined; 30 | } 31 | 32 | const config = { 33 | defaults: true, 34 | }; 35 | 36 | const [result, error] = await ofAnyCase(returnsVoid(), config); 37 | console.log(result); // undefined 38 | console.warn(error); // undefined 39 | ``` 40 | 41 | ?> You can use `ofIt()` or `Of.it()` to optimize execution 42 | 43 | --- 44 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Anton Trofimenko 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/core/ofSync.js: -------------------------------------------------------------------------------- 1 | import { ERR_UNKNOWN } from "../const/error.js"; 2 | 3 | import { isFunction } from "../util/isFunction.js"; 4 | 5 | /** 6 | * @name ofSync 7 | * @param {Function} callable 8 | * @param {[]=} args 9 | * @param {*=} defaultResult 10 | * @param {*=} overrideError 11 | * @returns {[*, unknown] | [undefined, *]} 12 | */ 13 | export function ofSync(callable, args, defaultResult, overrideError) { 14 | if (!isFunction(callable)) { 15 | return [undefined, new Error(ERR_UNKNOWN)]; 16 | } 17 | try { 18 | return [callable(...(Array.isArray(args) ? [...args] : [])), undefined]; 19 | } catch (caughtFunctionError) { 20 | let caughtError; 21 | if (overrideError instanceof Error) { 22 | caughtError = overrideError; 23 | } else if (typeof overrideError === "string") { 24 | caughtFunctionError.message = overrideError; 25 | caughtError = caughtFunctionError; 26 | } else if (caughtFunctionError === undefined || caughtFunctionError === null) { 27 | caughtError = new Error(ERR_UNKNOWN); 28 | } else { 29 | caughtError = caughtFunctionError; 30 | } 31 | return [defaultResult, caughtError]; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /docs/overwrite_error.md: -------------------------------------------------------------------------------- 1 | # 💔 Overwrite Error 2 | 3 | --- 4 | 5 | Sometimes you don't need the whole exact error or want to hide it. In an example, you need to provide an error message to the user. 6 | 7 | ```javascript 8 | async function databaseRequest() { 9 | throw "Your SQL query was not formed correctly. Whoops."; 10 | } 11 | 12 | const config = { 13 | error: new Error("Unable process your request."), 14 | }; 15 | 16 | const [result, error] = await ofAnyCase(databaseRequest(), config); 17 | console.log(result); // undefined 18 | console.warn(error); // "Unable process your request." 19 | ``` 20 | 21 | ?> You can use `ofIt()` or `Of.it()` to optimize execution 22 | 23 | --- 24 | 25 | Also, you can replace the error message and keep a stack trace. 26 | 27 | ```javascript 28 | async function databaseRequest() { 29 | throw "Error at line #2"; 30 | } 31 | 32 | const config = { 33 | error: "A custom error message, but the same stack trace", 34 | }; 35 | 36 | const [result, error] = await ofAnyCase(databaseRequest(), config); 37 | console.log(result); // undefined 38 | console.warn(error); // "A custom error message, but the same stack trace" 39 | ``` 40 | 41 | ?> You can use `ofIt()` or `Of.it()` to optimize execution 42 | 43 | --- 44 | -------------------------------------------------------------------------------- /docs/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "r37r0m0d3l", 3 | "default_locale": "en", 4 | "description": "OF - Promise wrapper with some sugar", 5 | "homepage_url": "https://of.js.org", 6 | "icons": [ 7 | { 8 | "src": "/icons/android-icon-36x36.png", 9 | "sizes": "36x36", 10 | "type": "image/png", 11 | "density": "0.75" 12 | }, 13 | { 14 | "src": "/icons/android-icon-48x48.png", 15 | "sizes": "48x48", 16 | "type": "image/png", 17 | "density": "1.0" 18 | }, 19 | { 20 | "src": "/icons/android-icon-72x72.png", 21 | "sizes": "72x72", 22 | "type": "image/png", 23 | "density": "1.5" 24 | }, 25 | { 26 | "src": "/icons/android-icon-96x96.png", 27 | "sizes": "96x96", 28 | "type": "image/png", 29 | "density": "2.0" 30 | }, 31 | { 32 | "src": "/icons/android-icon-144x144.png", 33 | "sizes": "144x144", 34 | "type": "image/png", 35 | "density": "3.0" 36 | }, 37 | { 38 | "src": "/icons/android-icon-192x192.png", 39 | "sizes": "192x192", 40 | "type": "image/png", 41 | "density": "4.0" 42 | } 43 | ], 44 | "manifest_version": 2, 45 | "name": "OF", 46 | "offline_enabled": true, 47 | "omnibox": { 48 | "keyword": "npm" 49 | }, 50 | "short_name": "OF", 51 | "version": "2021.09.22" 52 | } -------------------------------------------------------------------------------- /docs/usage.md: -------------------------------------------------------------------------------- 1 | # 💬 Usage 2 | 3 | --- 4 | 5 | ## Promise 6 | 7 | ```javascript 8 | const { ofAnyCase } = require("@await-of/of"); 9 | 10 | const promise = new Promise((resolve, _reject) => { 11 | resolve({ data: true }); 12 | }); 13 | 14 | const config = { 15 | defaults: "🤷 Default value in case of error", 16 | error: new Error("💀 Custom error, replaces thrown error"), 17 | timeout: 1000, // ⏱️ Delay before timeout error 18 | }; 19 | 20 | const [result, error] = await ofAnyCase(promise, config); // no error thrown 21 | 22 | console.log(result); // { data: true } 23 | console.warn(error); // no error thrown, so it's undefined 24 | ``` 25 | 26 | ?> You can use `ofCase()` or `Of.case()` to optimize execution 27 | 28 | --- 29 | 30 | ## Asynchronous Function 31 | 32 | ```javascript 33 | const { ofAnyCase } = require("@await-of/of"); 34 | 35 | async function asynchronous() { 36 | throw new Error("Unknown error"); 37 | } 38 | 39 | const config = { 40 | args: ["x", 1], 41 | defaults: "DEFAULT VALUE", 42 | error: new Error("CustomError"), 43 | retries: 3, // 🔁 Third time's a charm 44 | timeout: 1000 // ⏱️ Delay before timeout error 45 | }; 46 | 47 | const [result, error] = await ofAnyCase(asynchronous, config); // no error thrown 48 | 49 | console.log(result); // "DEFAULT VALUE" 50 | console.warn(error.message); // "CustomError" 51 | ``` 52 | 53 | --- 54 | -------------------------------------------------------------------------------- /src/core/ofCase.js: -------------------------------------------------------------------------------- 1 | import { ERR_UNKNOWN } from "../const/error.js"; 2 | 3 | /** 4 | * @name ofCase 5 | * @param {Promise} promise 6 | * @param {*=} config 7 | * @returns {Promise<[*, unknown] | [undefined, *]>} 8 | */ 9 | export function ofCase(promise, config = {}) { 10 | { 11 | const { args, defaults, error, timeout } = { ...config }; 12 | config = { args, defaults, error, timeout }; 13 | } 14 | if (config.timeout !== undefined) { 15 | const timeout = Number.parseInt(`${config.timeout}`); 16 | if (Number.isFinite(timeout) && timeout > 0) { 17 | config.timeout = timeout > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : timeout; 18 | } else { 19 | delete config.timeout; 20 | } 21 | } else { 22 | delete config.timeout; 23 | } 24 | return (config.timeout 25 | ? Promise.race([ 26 | Promise.resolve(promise), 27 | new Promise((_resolve, reject) => { 28 | setTimeout(() => reject(new Error(`Timeout: ${config.timeout}ms`)), config.timeout); 29 | }), 30 | ]) 31 | : Promise.resolve(promise) 32 | ) 33 | .then((result) => [result, undefined]) 34 | .catch((caughtError) => { 35 | if (caughtError === undefined || caughtError === null) { 36 | caughtError = new Error(ERR_UNKNOWN); 37 | } 38 | if (config.error instanceof Error) { 39 | caughtError = config.error; 40 | } else if (typeof config.error === "string") { 41 | caughtError.message = config.error; 42 | } 43 | return [config.defaults, caughtError]; 44 | }); 45 | } 46 | -------------------------------------------------------------------------------- /docs/retry.md: -------------------------------------------------------------------------------- 1 | # 🔄️ Retry 2 | 3 | --- 4 | 5 | Example of calling asynchronous function. You must pass asynchronous function not the promise. 6 | 7 | ```javascript 8 | async function tryMe() { 9 | // Useful code here… 10 | throw "Not gonna happen"; 11 | } 12 | 13 | const config = { 14 | args: [], // optional 15 | retries: 5, 16 | }; 17 | 18 | const [result, error] = await ofAnyCase(tryMe, config); 19 | console.log(result); // undefined 20 | console.log(error); // "Not gonna happen" 21 | ``` 22 | 23 | !> To run properly, you need to pass asynchronous function, not the promise. Rejected promise can't be used again! 24 | 25 | --- 26 | 27 | Example of calling an asynchronous function with parameters. 28 | 29 | ```javascript 30 | async function hello(name) { 31 | return `Hello, ${name}`; 32 | } 33 | 34 | const config = { 35 | args: ["John"], 36 | retries: 5, 37 | }; 38 | 39 | const [result, error] = await ofAnyCase(hello, config); 40 | console.log(result); // "Hello, John" 41 | console.log(error); // undefined 42 | ``` 43 | 44 | --- 45 | 46 | Example of reconnecting to the database. You must pass asynchronous function not the promise. 47 | 48 | ```javascript 49 | const mongoose = require("mongoose"); 50 | 51 | const URI = "mongodb://user:pass@host:1234/db"; 52 | 53 | async function connect(uri) { 54 | return mongoose.connect(uri); 55 | } 56 | 57 | const config = { 58 | args: [URI], 59 | retries: 5, 60 | }; 61 | 62 | const [connection, error] = await ofAnyCase(connect, config); 63 | if (error) { 64 | console.warn(`Error: ${error.message}`); 65 | process.exit(1); 66 | } 67 | console.log("Successfully connected!"); 68 | ``` 69 | 70 | --- 71 | -------------------------------------------------------------------------------- /docs/installation.md: -------------------------------------------------------------------------------- 1 | # 🚀 Installation 2 | 3 | --- 4 | 5 | ## 💾 NPM 6 | 7 | ```bash 8 | npm i @await-of/of 9 | ``` 10 | 11 | Install with alias name. 12 | 13 | ```bash 14 | npm i @npm:@await-of/of 15 | ``` 16 | 17 | Example: 18 | 19 | ```bash 20 | npm i of@npm:@await-of/of 21 | ``` 22 | 23 | ```javascript 24 | import { of, ofAnyCase, ofError } from "of"; // <- shortened name 25 | ``` 26 | 27 | ## 📈 Import 28 | 29 | CommonJS import. 30 | 31 | ```javascript 32 | const { 33 | Of, of, ofAny, ofAnyCase, ofCase, ofError, ofIt, ofOutcome, ofResult, ofSync 34 | } = require("@await-of/of"); 35 | ````` 36 | 37 | ECMAScript Module. 38 | 39 | ```javascript 40 | import { 41 | Of, of, ofAny, ofAnyCase, ofCase, ofError, ofIt, ofOutcome, ofResult, ofSync 42 | } from "@await-of/of"; 43 | ``` 44 | 45 | AMD, UMD, browser script tag. 46 | 47 | ```html 48 | 49 | ``` 50 | 51 | CDN (unpkg [https://unpkg.com/](https://unpkg.com/)) 52 | 53 | ```html 54 | 55 | ``` 56 | 57 | Deno import from URL. 58 | 59 | ```typescript 60 | // From URL 61 | import { of } from "https://deno.land/x/denof/mod.ts"; 62 | // Bundled from URL 63 | import { of } from "https://deno.land/x/denof/denof.bundle.js"; 64 | // Inline raw 65 | import { of } from "https://deno.land/x/denof/mod.ts"; 66 | // Inline bundle 67 | import { of } from "https://deno.land/x/denof/denof.bundle.js"; 68 | ``` 69 | 70 | Deno import from "importmap.json" 71 | 72 | ```json 73 | { 74 | "imports": { 75 | "denof": "https://deno.land/x/denof/mod.ts" 76 | } 77 | } 78 | ``` 79 | 80 | ```typescript 81 | import { of } from "denof"; 82 | ``` 83 | 84 | ```bash 85 | deno run --importmap=importmap.json --unstable your-script.js 86 | ``` 87 | 88 | --- 89 | -------------------------------------------------------------------------------- /docs/timeout.md: -------------------------------------------------------------------------------- 1 | # ⏲️ Timeout 2 | 3 | --- 4 | 5 | Example with asynchronous function execution. 6 | 7 | ```javascript 8 | async function doSomething() { 9 | return "Success"; 10 | } 11 | 12 | const config = { timeout: 1 }; // 1 ms 13 | 14 | const [result, error] = await ofAnyCase(doSomething(), config); 15 | 16 | console.warn(error); // undefined 17 | console.log(result); // "Success" 18 | ``` 19 | 20 | --- 21 | 22 | Example of reading a very huge JSON file. If the file is too large and we can't wait more than second. 23 | 24 | ```javascript 25 | const fs = require("fs"); 26 | 27 | function readConfig() { 28 | return new Promise((resolve, reject) => { 29 | fs.readFile("./large_config.json", "utf8", (error, data) => { 30 | if (error) { 31 | reject(error); 32 | } else { 33 | resolve(JSON.parse(data)); 34 | } 35 | }); 36 | }); 37 | } 38 | 39 | const config = { timeout: 1000 }; // 1 second 40 | 41 | const [result, error] = await ofAnyCase(readConfig(), config); 42 | 43 | console.warn(error.message); // 'Timeout: 1000ms' 44 | console.log(result); // undefined 45 | ``` 46 | 47 | ?> You can use `ofCase()` or `Of.case()` to optimize execution 48 | 49 | --- 50 | 51 | Example with AJAX request. If the problem on the server-side even when the connection was closed the script kept processing the data. Here we skipping the processing. 52 | 53 | ```javascript 54 | const axios = require("axios"); 55 | 56 | const url = "https://url_with_large_xml_to_process.xml"; 57 | 58 | const config = { timeout: 30000 }; // 30 secons 59 | 60 | const [result, error] = await ofAnyCase(axios.head(url), config); 61 | 62 | console.log(error.message); // 'Timeout: 30000ms' 63 | console.log(result); // undefined 64 | ``` 65 | 66 | ?> You can use `ofCase()` or `Of.case()` to optimize execution 67 | 68 | --- 69 | -------------------------------------------------------------------------------- /docs/callable_types.md: -------------------------------------------------------------------------------- 1 | # 🔰 Callable Types 2 | 3 | --- 4 | 5 | ## Promise 6 | 7 | ```javascript 8 | const promise = new Promise(resolve => resolve("OK")); 9 | const configuration = { 10 | retries: 10, // ignored only for promises! 11 | }; 12 | const [result, error] = await ofAnyCase(promise); 13 | console.log(result); // "OK" 14 | ``` 15 | 16 | !> Rejected promise can't be used again. `retries` option is ignored. 17 | 18 | ```javascript 19 | const promise = new Promise(resolve => resolve("OK")); 20 | const [result, error] = await of(promise); 21 | console.log(result); // "OK" 22 | ``` 23 | 24 | ?> You can use `of()` or `Of.async()` to optimize execution. But you must use other functions and methods for other callable types. 25 | 26 | --- 27 | 28 | ## Asynchronous Function 29 | 30 | ```javascript 31 | async function doSomething() { 32 | return "OK"; 33 | } 34 | const [result, error] = await ofAnyCase(doSomething); 35 | console.log(result); // "OK" 36 | ``` 37 | 38 | --- 39 | 40 | ## Asynchronous Function with parameters 41 | 42 | ```javascript 43 | async function doSomething(start, end) { 44 | return `${start}OK${end}`; 45 | } 46 | const configuration = { 47 | args: ["<", ">"], 48 | }; 49 | const [result, error] = await ofAnyCase(doSomething, configuration); 50 | console.log(result); // "" 51 | ``` 52 | 53 | --- 54 | 55 | ## Synchronous Function 56 | 57 | This is the only example. Probably there better solution for any synchronous execution. 58 | 59 | ```javascript 60 | function doSomething() { 61 | return "OK"; 62 | } 63 | const [result, error] = await ofAnyCase(doSomething); 64 | console.log(result); // "OK" 65 | ``` 66 | 67 | --- 68 | 69 | ## Generator Function 70 | 71 | ```javascript 72 | function* doGenerator() { 73 | yield 42; 74 | } 75 | const [result, error] = await ofAnyCase(doGenerator); 76 | console.log(result); // 42 77 | ``` 78 | 79 | ## Generator Object 80 | 81 | ```javascript 82 | function* doGenerator() { 83 | yield 1984; 84 | } 85 | const generator = doGenerator(); 86 | const [result, error] = await ofAnyCase(generator); 87 | console.log(result); // 1984 88 | ``` 89 | 90 | --- 91 | -------------------------------------------------------------------------------- /docs/how-to.md: -------------------------------------------------------------------------------- 1 | # 📚 How-to 2 | 3 | --- 4 | 5 | Code examples for every function. 6 | 7 | --- 8 | 9 | **of / Of.async** 10 | 11 | ```javascript 12 | const [result, error] = await of(promiseOrAsyncFunction); 13 | const [result, error] = await Of.async(promiseOrAsyncFunction); 14 | ``` 15 | 16 | **ofAny / Of.any** 17 | 18 | ```javascript 19 | const [result, error] = await ofAny(anyCallable, arrayOfArguments, defaultResult, overrideError); 20 | const [result, error] = await Of.any(anyCallable, arrayOfArguments, defaultResult, overrideError); 21 | ``` 22 | 23 | **ofAnyCase / Of.anyCase** 24 | 25 | ```javascript 26 | const [result, error] = await ofAnyCase(anyCallable, configuration); 27 | const [result, error] = await Of.anyCase(anyCallable, configuration); 28 | ``` 29 | 30 | **ofCase / Of.case** 31 | 32 | ```javascript 33 | const [result, error] = await ofCase(promiseOrAsyncFunction, configuration); 34 | const [result, error] = await Of.case(promiseOrAsyncFunction, configuration); 35 | ``` 36 | 37 | **ofError / Of.error** 38 | 39 | ```javascript 40 | const error = await ofError(promiseOrAsyncFunction, overrideError); 41 | const error = await Of.error(promiseOrAsyncFunction, overrideError); 42 | ``` 43 | 44 | **ofIt / Of.it** 45 | 46 | ```javascript 47 | const [result, error] = await ofIt(promiseOrAsyncFunction, defaultResult, overrideError); 48 | const [result, error] = await Of.it(promiseOrAsyncFunction, defaultResult, overrideError); 49 | ``` 50 | 51 | **ofOutcome / Of.outcome** 52 | 53 | ```javascript 54 | const resultOrError = await ofOutcome(anyCallable, configuration); 55 | const resultOrError = await Of.outcome(anyCallable, configuration); 56 | ``` 57 | 58 | **ofResult / Of.result** 59 | 60 | ```javascript 61 | const result = await ofResult(promiseOrAsyncFunction, defaultResult, overrideError); 62 | const result = await Of.result(promiseOrAsyncFunction, defaultResult, overrideError); 63 | ``` 64 | 65 | **ofSync / Of.sync** 66 | 67 | ```javascript 68 | const [result, error] = await ofSync(() => synchronousFunction, arrayOfArguments, defaultResult, overrideError); 69 | const [result, error] = await Of.sync(() => synchronousFunction, arrayOfArguments, defaultResult, overrideError); 70 | ``` 71 | 72 | --- 73 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 |

🍬 O F 🍬

2 | 3 | --- 4 | 5 |
Syntactic sugar for asynchronous functions, promises, generators and synchronous functions.
6 | 7 | This 🍬 OF ⬢ for `NodeJS`. `Deno` version of module - [🍬 DenOf 🦕](https://github.com/await-of/denof). 8 | 9 | [![NPM Version][npm-version-img]][npm-version-url] 10 | [![NPM Downloads][npm-downloads-img]][npm-downloads-url] 11 | [![GitHub Stars][gh-stars-img]][gh-stars-url] 12 | 13 | [![TypeScript Typings][ts-img]][ts-url] 14 | [![Travis CI][travis-img]][travis-url] 15 | 16 | [![Maintainability Rating][sonarcloud-img]][sonarcloud-url] 17 | [![LGTM][lgtm-img]][lgtm-url] 18 | [![Codacy Badge][codacy-img]][codacy-url] 19 | [![snyk][snyk-img]][snyk-url] 20 | 21 | ![OF](example.webp?raw=true "OF") 22 | 23 | 24 | 25 | [codacy-img]: https://app.codacy.com/project/badge/Grade/851db6300de44669bc92d7285b5d9cf1 26 | [codacy-url]: https://www.codacy.com/gh/await-of/of/dashboard?utm_source=github.com&utm_medium=referral&utm_content=await-of/of&utm_campaign=Badge_Grade 27 | [snyk-img]: https://snyk.io/test/github/await-of/of/badge.svg 28 | [snyk-url]: https://of.js.org/ 29 | [gh-stars-img]: https://badgen.net/github/stars/await-of/of?&icon=github&label=stars&color=FFCC33 30 | [gh-stars-url]: https://github.com/await-of/of 31 | [lgtm-img]: https://badgen.net/lgtm/grade/g/await-of/of?&icon=lgtm&label=lgtm:js/ts&color=00C853 32 | [lgtm-url]: https://lgtm.com/projects/g/await-of/of/ 33 | [npm-downloads-img]: https://badgen.net/npm/dt/@await-of/of?&icon=terminal&label=downloads&color=009688 34 | [npm-downloads-url]: https://npmjs.com/package/@await-of/of 35 | [npm-version-img]: https://badgen.net/npm/v/@await-of/of?&icon=npm&label=npm&color=DD3636 36 | [npm-version-url]: https://npmjs.com/package/@await-of/of 37 | [sonarcloud-img]: https://sonarcloud.io/api/project_badges/measure?project=await-of_of&metric=sqale_rating 38 | [sonarcloud-url]: https://sonarcloud.io/dashboard?id=await-of_of 39 | [travis-img]: https://badgen.net/travis/await-of/of?&icon=travis&label=build 40 | [travis-url]: https://travis-ci.org/github/await-of/of 41 | [ts-img]: https://badgen.net/npm/types/@await-of/of?&icon=typescript&label=types&color=1E90FF 42 | [ts-url]: https://github.com/await-of/of/blob/master/dist/of.d.ts 43 | -------------------------------------------------------------------------------- /src/core/ofAny.js: -------------------------------------------------------------------------------- 1 | import { ERR_UNKNOWN } from "../const/error.js"; 2 | import { FUNC, FUNC_ASYNC, FUNC_GEN, OBJ_GEN, PROMISE } from "../const/type.js"; 3 | 4 | /** 5 | * @name ofAny 6 | * @param {Function|Promise} callable 7 | * @param {[]=} args 8 | * @param {*=} defaultResult 9 | * @param {*=} overrideError 10 | * @returns {Promise<[*, unknown] | [undefined, *]>} 11 | */ 12 | export function ofAny(callable, args, defaultResult, overrideError) { 13 | let call; 14 | switch (callable.constructor.name || Object.prototype.toString.call(callable)) { 15 | case PROMISE: 16 | call = callable; 17 | break; 18 | case FUNC_ASYNC: 19 | call = callable(...(Array.isArray(args) ? [...args] : [])); 20 | break; 21 | case FUNC: 22 | call = new Promise((resolve, reject) => { 23 | try { 24 | resolve(callable(...(Array.isArray(args) ? [...args] : []))); 25 | } catch (caughtFunctionError) { 26 | reject(caughtFunctionError); 27 | } 28 | }); 29 | break; 30 | case FUNC_GEN: 31 | call = new Promise((resolve, reject) => { 32 | const gen = callable(...(Array.isArray(args) ? [...args] : [])); 33 | try { 34 | resolve(gen.next().value); 35 | } catch (caughtGeneratorFunctionError) { 36 | reject(caughtGeneratorFunctionError); 37 | } 38 | }); 39 | break; 40 | case OBJ_GEN: 41 | call = new Promise((resolve, reject) => { 42 | try { 43 | resolve(callable.next().value); 44 | } catch (caughtGeneratorError) { 45 | reject(caughtGeneratorError); 46 | } 47 | }); 48 | break; 49 | default: 50 | call = new Promise((resolve, reject) => { 51 | Promise.resolve(callable).then(resolve).catch(reject); 52 | }); 53 | } 54 | return Promise.resolve(call) 55 | .then((result) => [result]) 56 | .catch((caughtError) => { 57 | if (caughtError === undefined || caughtError === null) { 58 | caughtError = new Error(ERR_UNKNOWN); 59 | } 60 | if (overrideError instanceof Error) { 61 | caughtError = overrideError; 62 | } else if (typeof overrideError === "string") { 63 | caughtError.message = overrideError; 64 | } 65 | return [defaultResult, caughtError]; 66 | }); 67 | } 68 | -------------------------------------------------------------------------------- /_layouts/default.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 12 | 13 | {% seo %} 14 | 15 | 16 | 17 |
18 |
19 |
20 | {% if site.show_downloads %} 21 | Download .zip 22 | Download .tar.gz 23 | {% endif %} 24 | {% if site.github.public %} 25 | {% if site.github.is_project_page %} 26 | View on GitHub 27 | {% else %} 28 | View on GitHub 29 | {% endif %} 30 | {% endif %} 31 |
32 |
33 |
34 | {{ content }} 35 |
36 | 37 |
38 | {% if site.github.is_project_page %} 39 | {{ site.title | default: site.github.repository_name }} is maintained by {{ site.github.owner_name }}
40 | {% endif %} 41 | This page was generated by GitHub Pages. 42 |
43 | 44 |
45 |
46 | 47 | {% if site.google_analytics %} 48 | 56 | {% endif %} 57 | 58 | -------------------------------------------------------------------------------- /docs/about.md: -------------------------------------------------------------------------------- 1 | # 🤔 About 2 | 3 | --- 4 | 5 | OF is async / await wrapper for easy error handling, retriable asynchronous function calls, execution timeouts, default values, and errors. 6 | 7 | 9 | 34 | 51 | 76 |
8 |
10 | 11 | ```javascript 12 | // Vanilla JavaScript 13 | 14 | async function doAsync() { 15 | return true; 16 | } 17 | let result; 18 | let error; 19 | try { 20 | result = await doAsync(); 21 | } catch(err) { 22 | error = err; 23 | } 24 | if (error) { 25 | // Error 26 | console.warn(error); 27 | } else { 28 | // Success 29 | console.log(result); 30 | } 31 | ``` 32 | 33 | 35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
52 | 53 | ```javascript 54 | // Basic library usage 55 | 56 | async function doAsync() { 57 | return true; 58 | } 59 | const [result, error] = await ofAnyCase(doAsync); 60 | if (error) { 61 | // Error 62 | console.warn(error); 63 | } else { 64 | // Success 65 | console.log(result); 66 | } 67 | 68 | 69 | 70 | 71 | 72 | 73 | ``` 74 | 75 |
77 | 78 | --- 79 | 80 | However, it's basic usage very straightforward and can be handled differently by developers. 81 | The main aim is to create the Swiss Army Knife for asynchronous code. 82 | What actually it solves? 83 | 84 | - It accepts asynchronous functions, promises, synchronous functions, generator functions, and objects. In case you messed up with the parameters or don't want to do extra code. 85 | 86 | - It gets rid of endless try/catch if you have to write a very complex code where every step should be checked for errors. 87 | 88 | - Not only AJAX requests need timeouts. 89 | Long time response from the server, parsing, selecting something from the database, etc. should be handled in the same way as asynchronous operations. 90 | The wrapper can be used when the server connection was closed but the script keeps processing data almost infinitely after that. 91 | 92 | - Retry configuration can be used not only for AJAX requests (refresh token in the example) but also for MongoDB read/write functions. 93 | 94 | - Default values can be used when there is no good result but you actually don't care about reasons why this happens. 95 | 96 | - You can overwrite errors on the fly. In an example, you can use one error string for many asynchronous code executions. 97 | 98 | --- 99 | -------------------------------------------------------------------------------- /src/class/Of.js: -------------------------------------------------------------------------------- 1 | import { ofAny } from "../core/ofAny.js"; 2 | import { ofAnyCase } from "../core/ofAnyCase.js"; 3 | import { ofCase } from "../core/ofCase.js"; 4 | import { ofError } from "../core/ofError.js"; 5 | import { ofIt } from "../core/ofIt.js"; 6 | import { of } from "../core/of.js"; 7 | import { ofResult } from "../core/ofResult.js"; 8 | import { ofSync } from "../core/ofSync.js"; 9 | import { ofOutcome } from "../core/ofOutcome.js"; 10 | 11 | export class Of { 12 | /** 13 | * @name any 14 | * @alias ofAny 15 | * @public 16 | * @static 17 | * @method 18 | * @param {Function|Promise} callable 19 | * @param {[]=} args 20 | * @param {*=} defaultResult 21 | * @param {*=} overrideError 22 | * @returns {Promise<[*, unknown] | [undefined, *]>} 23 | */ 24 | static any = ofAny; 25 | /** 26 | * @name anyCase 27 | * @alias ofAnyCase 28 | * @public 29 | * @static 30 | * @method 31 | * @param {Function|Promise} callable 32 | * @param {*=} config 33 | * @returns {Promise<[*, unknown] | [undefined, *]>} 34 | */ 35 | static anyCase = ofAnyCase; 36 | /** 37 | * @name case 38 | * @alias ofCase 39 | * @public 40 | * @static 41 | * @method 42 | * @param {Promise} promise 43 | * @param {*=} config 44 | * @returns {Promise<[*, unknown] | [undefined, *]>} 45 | */ 46 | static case = ofCase; 47 | /** 48 | * @name error 49 | * @alias ofError 50 | * @public 51 | * @static 52 | * @method 53 | * @param {Promise} promise 54 | * @param {*=} overrideError 55 | * @returns {Promise<*>} 56 | */ 57 | static error = ofError; 58 | /** 59 | * @name it 60 | * @alias ofIt 61 | * @public 62 | * @static 63 | * @method 64 | * @param {Promise} promise 65 | * @param {*=} defaultResult 66 | * @param {*=} overrideError 67 | * @returns {Promise<[*, unknown] | [undefined, *]>} 68 | */ 69 | static it = ofIt; 70 | /** 71 | * @name async 72 | * @alias of 73 | * @public 74 | * @static 75 | * @method 76 | * @param {Promise} promise 77 | * @returns {Promise<[*, unknown] | [undefined, *]>} 78 | */ 79 | static async = of; 80 | /** 81 | * @name result 82 | * @alias ofResult 83 | * @public 84 | * @static 85 | * @method 86 | * @param {Promise} promise 87 | * @param {*=} defaultResult 88 | * @returns {Promise<*>} 89 | */ 90 | static result = ofResult; 91 | /** 92 | * @name sync 93 | * @alias ofSync 94 | * @public 95 | * @static 96 | * @method 97 | * @param {Function} callable 98 | * @param {[]=} args 99 | * @param {*=} defaultResult 100 | * @param {*=} overrideError 101 | * @returns {[*, unknown] | [undefined, *]} 102 | */ 103 | static sync = ofSync; 104 | /** 105 | * @name outcome 106 | * @alias ofOutcome 107 | * @public 108 | * @static 109 | * @method 110 | * @param {Function|Promise} callable 111 | * @param {*=} config 112 | * @returns {Promise<[*, unknown] | [undefined, *]>} 113 | */ 114 | static outcome = ofOutcome; 115 | } 116 | -------------------------------------------------------------------------------- /docs/functions.md: -------------------------------------------------------------------------------- 1 | # 💡️ Functions 2 | 3 | --- 4 | 5 | To optimize the application, it is recommended to select a specific function from list. 6 | 7 | --- 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 |
↘️Resolves
Promise
Catches
Error
Returns
Error
Custom
Error
Executes
Any
Function
Retry
Execution
Execution
Timeout
Custom
Default
Result
of()
Of.async()
✔️✔️✔️
ofAny()
Of.any()
✔️✔️✔️✔️✔️
ofAnyCase()
Of.anyCase()
✔️✔️✔️✔️✔️✔️✔️✔️
ofCase()
Of.case()
✔️✔️✔️✔️✔️✔️✔️
ofError()
Of.error()
✔️✔️✔️✔️
ofIt()
Of.it()
✔️✔️✔️✔️✔️
ofOutcome()
Of.outcome()
✔️✔️✔️✔️✔️✔️✔️✔️
ofResult()
Of.result()
✔️✔️✔️
ofSync()
Of.sync()
✔️✔️✔️✔️
125 | 126 | --- 127 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "Anton Trofimenko", 3 | "bugs": { 4 | "url": "https://github.com/await-of/of/issues" 5 | }, 6 | "contributors": [ 7 | { 8 | "email": "r37r0m0d3l@protonmail.com", 9 | "name": "Anton Trofimenko" 10 | } 11 | ], 12 | "dependencies": {}, 13 | "description": "Promise wrapper with some sugar", 14 | "devDependencies": { 15 | "@babel/core": "7.15.5", 16 | "@babel/plugin-proposal-class-properties": "7.14.5", 17 | "@babel/plugin-proposal-private-methods": "7.14.5", 18 | "@babel/preset-env": "7.15.6", 19 | "@r37r0m0d3l/rollup-config-pkg": "git+https://github.com/r37r0m0d3l/rollup-config-pkg.git", 20 | "@rollup/plugin-commonjs": "20.0.0", 21 | "@rollup/plugin-node-resolve": "13.0.5", 22 | "babel-core": "7.0.0-bridge.0", 23 | "babel-eslint": "10.1.0", 24 | "eslint": "7.32.0", 25 | "eslint-config-prettier": "8.3.0", 26 | "eslint-plugin-prettier": "4.0.0", 27 | "jest": "27.2.1", 28 | "npm-check": "5.9.2", 29 | "prettier": "2.4.1", 30 | "remark-cli": "10.0.0", 31 | "remark-lint": "9.1.0", 32 | "remark-preset-lint-consistent": "5.1.0", 33 | "remark-preset-lint-markdown-style-guide": "5.1.0", 34 | "remark-preset-lint-recommended": "6.1.0", 35 | "rollup": "2.57.0", 36 | "rollup-plugin-babel": "4.4.0", 37 | "rollup-plugin-terser": "7.0.2" 38 | }, 39 | "engines": { 40 | "node": ">=12.16.3" 41 | }, 42 | "engineStrict": false, 43 | "exports": { 44 | ".": { 45 | "browser": { 46 | "import": "./dist/of.mjs", 47 | "require": "./dist/of.cjs" 48 | }, 49 | "node": { 50 | "import": "./dist/of.mjs", 51 | "require": "./dist/of.cjs" 52 | }, 53 | "import": "./dist/of.mjs", 54 | "require": "./dist/of.cjs", 55 | "default": "./dist/of.js" 56 | } 57 | }, 58 | "files": [ 59 | "dist/of.cjs", 60 | "dist/of.cjs.map", 61 | "dist/of.d.ts", 62 | "dist/of.js", 63 | "dist/of.js.map", 64 | "dist/of.mjs", 65 | "dist/of.mjs.map" 66 | ], 67 | "homepage": "https://of.js.org", 68 | "keywords": [ 69 | "async await", 70 | "async", 71 | "await", 72 | "error swallowing", 73 | "errors handling", 74 | "promise", 75 | "try-catch", 76 | "wrapper" 77 | ], 78 | "license": "MIT", 79 | "main": "./dist/of.cjs", 80 | "module": "./dist/of.mjs", 81 | "name": "@await-of/of", 82 | "repository": { 83 | "type": "git", 84 | "url": "git+https://github.com/await-of/of.git" 85 | }, 86 | "scripts": { 87 | "build": "rollup --config rollup.config.mjs", 88 | "build:watch": "rollup --config rollup.config.mjs --watch", 89 | "docs:serve": "docsify serve docs", 90 | "lint": "eslint ./src/**/*.js", 91 | "lint:md": "remark .", 92 | "package:pack": "npm prune --production && npm shrinkwrap", 93 | "package:upgrade": "npx npm-check --update", 94 | "test": "jest", 95 | "test:coverage": "jest --collect-coverage" 96 | }, 97 | "type": "module", 98 | "types": "./dist/of.d.ts", 99 | "version": "2.4.10", 100 | "optionalDependencies": { 101 | "fsevents": "2.3.2" 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🍡🍭🍬 O F 🍡🍭🍬 2 | 3 | [https://of.js.org/](https://of.js.org) 4 | 5 |
Syntactic sugar for asynchronous functions, promises, generators and synchronous functions.
6 | 7 | Deno version of module - [🍬🦕 DenOf 🍬🦕](https://github.com/await-of/denof). 8 | 9 | [![NPM Version][npm-version-img]][npm-version-url] 10 | [![NPM Downloads][npm-downloads-img]][npm-downloads-url] 11 | [![GitHub Stars][gh-stars-img]][gh-stars-url] 12 | 13 | [![TypeScript Typings][ts-img]][ts-url] 14 | [![Travis CI][travis-img]][travis-url] 15 | 16 | [![Maintainability Rating][sonarcloud-img]][sonarcloud-url] 17 | [![LGTM][lgtm-img]][lgtm-url] 18 | [![Codacy Badge][codacy-img]][codacy-url] 19 | [![Snyk][snyk-img]][snyk-url] 20 | 21 | ![OF](docs/example.webp?raw=true "OF") 22 | 23 | ## 💬 Usage 24 | 25 | ```javascript 26 | import { ofAnyCase } from "@await-of/of"; 27 | const promise = () => new Promise((resolve, _reject) => { 28 | resolve({ data: true }); 29 | }); 30 | const config = { 31 | defaults: "🤷 Default value in case of error", 32 | error: new Error("💀 Custom error, replaces thrown error"), 33 | retries: 3, // 🔁 Third time's a charm 34 | timeout: 1000, // ⏱️ Delay before timeout error 35 | }; 36 | // no error thrown 37 | const [result, error] = await ofAnyCase(promise(), config); 38 | console.log(result); // { data: true } 39 | console.warn(error); // no error thrown, so it's undefined 40 | ``` 41 | 42 | ## 🗺️ Discover more 43 | 44 | [My other projects](https://r37r0m0d3l.icu/open_source_map) 45 | 46 | 47 | 48 | 49 | 50 | [codacy-img]: https://app.codacy.com/project/badge/Grade/851db6300de44669bc92d7285b5d9cf1 51 | [codacy-url]: https://www.codacy.com/gh/await-of/of/dashboard?utm_source=github.com&utm_medium=referral&utm_content=await-of/of&utm_campaign=Badge_Grade 52 | [snyk-img]: https://snyk.io/test/github/await-of/of/badge.svg 53 | [snyk-url]: https://of.js.org/ 54 | [gh-stars-img]: https://badgen.net/github/stars/await-of/of?&icon=github&label=stars&color=FFCC33 55 | [gh-stars-url]: https://github.com/await-of/of 56 | [lgtm-img]: https://badgen.net/lgtm/grade/g/await-of/of?&icon=lgtm&label=lgtm:js/ts&color=00C853 57 | [lgtm-url]: https://lgtm.com/projects/g/await-of/of/ 58 | [npm-downloads-img]: https://badgen.net/npm/dt/@await-of/of?&icon=terminal&label=downloads&color=009688 59 | [npm-downloads-url]: https://npmjs.com/package/@await-of/of 60 | [npm-version-img]: https://badgen.net/npm/v/@await-of/of?&icon=npm&label=npm&color=DD3636 61 | [npm-version-url]: https://npmjs.com/package/@await-of/of 62 | [sonarcloud-img]: https://sonarcloud.io/api/project_badges/measure?project=await-of_of&metric=sqale_rating 63 | [sonarcloud-url]: https://sonarcloud.io/dashboard?id=await-of_of 64 | [travis-img]: https://badgen.net/travis/await-of/of?&icon=travis&label=build 65 | [travis-url]: https://travis-ci.org/github/await-of/of 66 | [ts-img]: https://badgen.net/npm/types/@await-of/of?&icon=typescript&label=types&color=1E90FF 67 | [ts-url]: https://github.com/await-of/of/blob/master/dist/of.d.ts 68 | -------------------------------------------------------------------------------- /docs/sw.js: -------------------------------------------------------------------------------- 1 | /* =========================================================== 2 | * docsify sw.js 3 | * =========================================================== 4 | * Copyright 2016 @huxpro 5 | * Licensed under Apache 2.0 6 | * Register service worker. 7 | * ========================================================== */ 8 | 9 | const RUNTIME = "docsify"; 10 | const HOSTNAME_WHITELIST = [self.location.hostname, "fonts.gstatic.com", "fonts.googleapis.com", "unpkg.com"]; 11 | 12 | // The Util Function to hack URLs of intercepted requests 13 | const getFixedUrl = (req) => { 14 | var now = Date.now(); 15 | var url = new URL(req.url); 16 | 17 | // 1. fixed http URL 18 | // Just keep syncing with location.protocol 19 | // fetch(httpURL) belongs to active mixed content. 20 | // And fetch(httpRequest) is not supported yet. 21 | url.protocol = self.location.protocol; 22 | 23 | // 2. add query for caching-busting. 24 | // Github Pages served with Cache-Control: max-age=600 25 | // max-age on mutable content is error-prone, with SW life of bugs can even extend. 26 | // Until cache mode of Fetch API landed, we have to workaround cache-busting with query string. 27 | // Cache-Control-Bug: https://bugs.chromium.org/p/chromium/issues/detail?id=453190 28 | if (url.hostname === self.location.hostname) { 29 | url.search += (url.search ? "&" : "?") + "cache-bust=" + now; 30 | } 31 | return url.href; 32 | }; 33 | 34 | /** 35 | * @Lifecycle Activate 36 | * New one activated when old isnt being used. 37 | * 38 | * waitUntil(): activating ====> activated 39 | */ 40 | self.addEventListener("activate", (event) => { 41 | event.waitUntil(self.clients.claim()); 42 | }); 43 | 44 | /** 45 | * @Functional Fetch 46 | * All network requests are being intercepted here. 47 | * 48 | * void respondWith(Promise r) 49 | */ 50 | self.addEventListener("fetch", (event) => { 51 | // Skip some of cross-origin requests, like those for Google Analytics. 52 | if (HOSTNAME_WHITELIST.indexOf(new URL(event.request.url).hostname) > -1) { 53 | // Stale-while-revalidate 54 | // similar to HTTP's stale-while-revalidate: https://www.mnot.net/blog/2007/12/12/stale 55 | // Upgrade from Jake's to Surma's: https://gist.github.com/surma/eb441223daaedf880801ad80006389f1 56 | const cached = caches.match(event.request); 57 | const fixedUrl = getFixedUrl(event.request); 58 | const fetched = fetch(fixedUrl, { cache: "no-store" }); 59 | const fetchedCopy = fetched.then((resp) => resp.clone()); 60 | 61 | // Call respondWith() with whatever we get first. 62 | // If the fetch fails (e.g disconnected), wait for the cache. 63 | // If there’s nothing in cache, wait for the fetch. 64 | // If neither yields a response, return offline pages. 65 | event.respondWith( 66 | Promise.race([fetched.catch((_) => cached), cached]) 67 | .then((resp) => resp || fetched) 68 | .catch((_) => { 69 | /* eat any errors */ 70 | }), 71 | ); 72 | 73 | // Update the cache with the version we fetched (only for ok status) 74 | event.waitUntil( 75 | Promise.all([fetchedCopy, caches.open(RUNTIME)]) 76 | .then(([response, cache]) => response.ok && cache.put(event.request, response)) 77 | .catch((_) => { 78 | /* eat any errors */ 79 | }), 80 | ); 81 | } 82 | }); 83 | -------------------------------------------------------------------------------- /BADGES.md: -------------------------------------------------------------------------------- 1 | #### Codacy 2 | 3 | [![codacy](https://badgen.net/codacy/grade/eae5f883a3cf46178ffc8c949ed8278c)](https://github.com/await-of/of) 4 | 5 | [![Codacy Badge](https://api.codacy.com/project/badge/Grade/eae5f883a3cf46178ffc8c949ed8278c)](https://www.codacy.com/manual/await-of/of?utm_source=github.com&utm_medium=referral&utm_content=await-of/of&utm_campaign=Badge_Grade) 6 | 7 | #### Code Climate 8 | 9 | [![Maintainability](https://api.codeclimate.com/v1/badges/452e3e4bee15238ea29c/maintainability)](https://codeclimate.com/github/await-of/of/maintainability) 10 | 11 | #### DeepScan 12 | 13 | [![DeepScan grade](https://deepscan.io/api/teams/8453/projects/10648/branches/149673/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=8453&pid=10648&bid=149673) 14 | 15 | #### Dependabot 16 | 17 | [![Dependabot](https://badgen.net/dependabot/await-of/of?&icon=dependabot)](https://github.com/await-of/of) 18 | 19 | #### GitHub 20 | 21 | [![Combined Checks](https://badgen.net/github/checks/await-of/of?&icon=github)](https://github.com/await-of/of) 22 | [![Combined Status](https://badgen.net/github/status/await-of/of?&icon=github)](https://github.com/await-of/of) 23 | [![Types](https://badgen.net/npm/types/@await-of/of?&icon=typescript)](https://github.com/@await-of/of) 24 | [![Stars](https://badgen.net/github/stars/await-of/of?&icon=github&label=stars&color=ffcc33&v=1.4.0)](https://github.com/await-of/of) 25 | 26 | [![GitHub stars](https://img.shields.io/github/stars/await-of/of.svg?style=social&label=Star)](https://github.com/await-of/of) 27 | [![GitHub followers](https://img.shields.io/github/followers/r37r0m0d3l.svg?style=social&label=Follow)](https://github.com/r37r0m0d3l) 28 | 29 | #### NPM 30 | 31 | [![npm](https://badgen.net/npm/v/@await-of/of?&icon=npm)](https://www.npmjs.com/package/@await-of/of) 32 | [![downloads](https://badgen.net/npm/dt/@await-of/of?&icon=terminal)](https://www.npmjs.com/package/@await-of/of) 33 | 34 | [![NPM Version](https://img.shields.io/npm/v/@await-of/of.svg?style=flat)](https://www.npmjs.com/package/@await-of/of) 35 | [![NPM Downloads](https://img.shields.io/npm/dt/@await-of/of.svg?style=flat)](https://www.npmjs.com/package/@await-of/of) 36 | 37 | #### LGTM 38 | 39 | [![lgtm](https://badgen.net/lgtm/langs/g/await-of/of?&icon=lgtm)](https://github.com/await-of/of) 40 | [![lgtm](https://badgen.net/lgtm/grade/g/await-of/of?&icon=lgtm)](https://github.com/await-of/of) 41 | 42 | [![Total alerts](https://img.shields.io/lgtm/alerts/g/await-of/of.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/await-of/of/alerts/) 43 | [![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/await-of/of.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/await-of/of/context:javascript) 44 | 45 | #### Snyk 46 | 47 | ![Known Vulnerabilities](https://snyk.io/test/github/await-of/of/badge.svg) 48 | 49 | #### Sonar Cloud 50 | 51 | [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=await-of_of&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=await-of_of) 52 | [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=await-of_of&metric=alert_status)](https://sonarcloud.io/dashboard?id=await-of_of) 53 | 54 | #### Travis CI 55 | 56 | [![Build Status](https://badgen.net/travis/await-of/of?&icon=travis)](https://travis-ci.org/await-of/of) 57 | 58 | [![Build Status](https://travis-ci.org/await-of/of.svg?branch=master)](https://travis-ci.org/await-of/of) 59 | -------------------------------------------------------------------------------- /docs/changelog.md: -------------------------------------------------------------------------------- 1 | # 🆕 Changelog 2 | 3 | --- 4 | 5 | ## 2.4.10 6 | 7 | - ⬆️ Dependencies updated 8 | 9 | - 📚 Documentation updated 10 | 11 | --- 12 | 13 | ## 2.4.9 14 | 15 | - ⬆️ Dependencies updated 16 | 17 | --- 18 | 19 | ## 2.4.8 20 | 21 | - 🔥 Renamed into '@await-of/of' 22 | 23 | --- 24 | 25 | ## 2.4.7 26 | 27 | - 🔥 Removed unnecessary `Readonly` definitions in typings 28 | 29 | - ⬆️ Dependencies updated 30 | 31 | --- 32 | 33 | ## 2.4.6 34 | 35 | - 🐛️ Fix broken timeouts 36 | 37 | --- 38 | 39 | ## 2.4.5 40 | 41 | - 🐛️ Fix `npm-shrinkwrap.json` 42 | 43 | --- 44 | 45 | ## 2.4.4 46 | 47 | - 📚 Documentation updated 48 | 49 | - ⬆️ Dependencies updated 50 | 51 | --- 52 | 53 | ## 2.4.3 54 | 55 | - ⬆️ Dependencies updated 56 | 57 | --- 58 | 59 | ## 2.4.2 60 | 61 | - 📚 Documentation updated 62 | 63 | - ⬆️ Dependencies updated 64 | 65 | --- 66 | 67 | ## 2.4.1 68 | 69 | - 📚 Documentation updated 70 | 71 | - ⬆️ Dependencies updated 72 | 73 | --- 74 | 75 | ## 2.4.0 76 | 77 | - ➕ Added `ofOutcome` function 78 | 79 | - ➕ Added `Of.outcome` static method 80 | 81 | - 📚 Documentation updated 82 | 83 | - ⬆️ Dependencies updated 84 | 85 | --- 86 | 87 | ## 2.3.2 88 | 89 | - 🔥 Remove `package-lock.json` 90 | 91 | --- 92 | 93 | ## 2.3.1 94 | 95 | - 📚 Documentation updated 96 | 97 | - ⬆️ Dependencies updated 98 | 99 | --- 100 | 101 | ## 2.3.0 102 | 103 | - ➕ Added `ofSync` 104 | 105 | - 📚 Documentation updated 106 | 107 | - ⬆️ Dependencies updated 108 | 109 | --- 110 | 111 | ## 2.2.1 112 | 113 | - ⬆️ Dependencies updated 114 | 115 | --- 116 | 117 | ## 2.2.0 118 | 119 | - ⚡️ Change default export format 120 | 121 | - ⬆️ Dependencies updated 122 | 123 | - 📚 Documentation updated 124 | 125 | --- 126 | 127 | ## 2.1.4 128 | 129 | - ⬆️ Dependencies updated 130 | 131 | --- 132 | 133 | ## 2.1.3 134 | 135 | - ⬆️ Dependencies updated 136 | 137 | --- 138 | 139 | ## 2.1.2 140 | 141 | - ⬆️ Dependencies updated 142 | 143 | --- 144 | 145 | ## 2.1.1 146 | 147 | - ⬆️ Dependencies updated 148 | 149 | --- 150 | 151 | ## 2.1.0 152 | 153 | - ➕ Added `ofError` 154 | 155 | - 📚 Documentation updated 156 | 157 | - ⬆️ Dependencies updated 158 | 159 | --- 160 | 161 | ## 2.0.1 162 | 163 | - 📚 Documentation updated 164 | 165 | --- 166 | 167 | ## 2.0.0 168 | 169 | - 🐎️ Split library into separate components. 170 | 171 | --- 172 | 173 | ## 1.4.1 174 | 175 | - 🐎️ Minor optimizations. 176 | 177 | --- 178 | 179 | ## 1.4.0 180 | 181 | - 🏗️️ Making architectural changes. OF now can resolve values. 182 | 183 | --- 184 | 185 | ## 1.3.0 186 | 187 | - 🔥️ Default exports removed. 188 | 189 | --- 190 | 191 | ## 1.2.0 192 | 193 | - ♻️ Configuration property `error` now accepts a string as an error message. 194 | 195 | --- 196 | 197 | ## 1.1.3 198 | 199 | - ⬆️ Dependencies updated 200 | 201 | --- 202 | 203 | ## 1.1.2 204 | 205 | - 📚 Documentation updated 206 | 207 | --- 208 | 209 | ## 1.1.1 210 | 211 | - 📚 Documentation updated 212 | 213 | --- 214 | 215 | ## 1.1.0 216 | 217 | - 📚 Documentation updated 218 | 219 | - ➕ Added option to use synchronous functions 220 | 221 | ## 1.0.6 222 | 223 | - 📚 Documentation updated 224 | 225 | ## 1.0.5 226 | 227 | - 📚 Documentation updated 228 | 229 | ## 1.0.4 230 | 231 | - ⬆️ Dependencies updated 232 | 233 | ## 1.0.3 234 | 235 | - 🗜️ Minify distribution folder 236 | 237 | ## 1.0.2 238 | 239 | - 📚 Documentation updated 240 | 241 | ## 1.0.1 242 | 243 | - 📚 Documentation updated 244 | 245 | ## 1.0.0 246 | 247 | - 🎉 Initial release 248 | 249 | --- 250 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | - Using welcoming and inclusive language 18 | - Being respectful of differing viewpoints and experiences 19 | - Gracefully accepting constructive criticism 20 | - Focusing on what is best for the community 21 | - Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | - The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | - Trolling, insulting/derogatory comments, and personal or political attacks 28 | - Public or private harassment 29 | - Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | - Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at [r37r0m0d3l@protonmail.com](r37r0m0d3l@protonmail.com). All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 1.4, 71 | available at [https://www.contributor-covenant.org/version/1/4/code-of-conduct.html](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html) 72 | 73 | For answers to common questions about this code of conduct, see 74 | [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq) 75 | -------------------------------------------------------------------------------- /src/core/ofAnyCase.js: -------------------------------------------------------------------------------- 1 | import { ERR_UNKNOWN } from "../const/error.js"; 2 | import { FUNC, FUNC_ASYNC, FUNC_GEN, OBJ_GEN, PROMISE } from "../const/type.js"; 3 | 4 | /** 5 | * @name ofAnyCase 6 | * @param {Function|Promise} callable 7 | * @param {*=} config 8 | * @returns {Promise<[*, unknown] | [undefined, *]>} 9 | */ 10 | export function ofAnyCase(callable, config = {}) { 11 | { 12 | const { args, defaults, error, retries, timeout } = { ...config }; 13 | config = { args, defaults, error, retries, timeout }; 14 | } 15 | let call; 16 | switch (callable.constructor.name || Object.prototype.toString.call(callable)) { 17 | case PROMISE: 18 | call = callable; 19 | config.retries = 0; 20 | delete config.args; 21 | break; 22 | case FUNC_ASYNC: 23 | call = callable(...(Array.isArray(config.args) ? [...config.args] : [])); 24 | break; 25 | case FUNC: 26 | call = new Promise((resolve, reject) => { 27 | try { 28 | resolve(callable(...(Array.isArray(config.args) ? [...config.args] : []))); 29 | } catch (caughtFunctionError) { 30 | reject(caughtFunctionError); 31 | } 32 | }); 33 | break; 34 | case FUNC_GEN: 35 | call = new Promise((resolve, reject) => { 36 | const gen = callable(...(Array.isArray(config.args) ? [...config.args] : [])); 37 | try { 38 | resolve(gen.next().value); 39 | } catch (caughtGeneratorFunctionError) { 40 | reject(caughtGeneratorFunctionError); 41 | } 42 | }); 43 | break; 44 | case OBJ_GEN: 45 | call = new Promise((resolve, reject) => { 46 | try { 47 | resolve(callable.next().value); 48 | } catch (caughtGeneratorError) { 49 | reject(caughtGeneratorError); 50 | } 51 | }); 52 | delete config.args; 53 | break; 54 | default: 55 | call = new Promise((resolve, reject) => { 56 | Promise.resolve(callable).then(resolve).catch(reject); 57 | }); 58 | delete config.args; 59 | } 60 | if (config.timeout !== undefined) { 61 | const timeout = Number.parseInt(`${config.timeout}`); 62 | if (Number.isFinite(timeout) && timeout > 0) { 63 | config.timeout = timeout > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : timeout; 64 | } else { 65 | delete config.timeout; 66 | } 67 | } else { 68 | delete config.timeout; 69 | } 70 | return (config.timeout 71 | ? Promise.race([ 72 | Promise.resolve(call), 73 | new Promise((_resolve, reject) => { 74 | setTimeout(() => reject(new Error(`Timeout: ${config.timeout}ms`)), config.timeout); 75 | }), 76 | ]) 77 | : Promise.resolve(call) 78 | ) 79 | .then((result) => [result]) 80 | .catch((caughtError) => { 81 | if (config.retries !== undefined) { 82 | const retries = Number.parseInt(config.retries); 83 | if (Number.isFinite(retries) && retries > 0) { 84 | config.retries = retries > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : retries; 85 | } else { 86 | delete config.retries; 87 | } 88 | } else { 89 | delete config.retries; 90 | } 91 | if (config.retries) { 92 | config.attempt = config.attempt === undefined ? 0 : config.attempt + 1; 93 | if (config.attempt < config.retries) { 94 | return ofAnyCase(callable, config); 95 | } 96 | } 97 | if (caughtError === undefined || caughtError === null) { 98 | caughtError = new Error(ERR_UNKNOWN); 99 | } 100 | if (config.error instanceof Error) { 101 | caughtError = config.error; 102 | } else if (typeof config.error === "string") { 103 | caughtError.message = config.error; 104 | } 105 | return [config.defaults, caughtError]; 106 | }); 107 | } 108 | -------------------------------------------------------------------------------- /dist/of.mjs: -------------------------------------------------------------------------------- 1 | function _defineProperty(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}const e="Unknown Error";function ofAny(r,t,o,n){let s;switch(r.constructor.name||Object.prototype.toString.call(r)){case"Promise":s=r;break;case"AsyncFunction":s=r(...Array.isArray(t)?[...t]:[]);break;case"Function":s=new Promise((e,o)=>{try{e(r(...Array.isArray(t)?[...t]:[]))}catch(e){o(e)}});break;case"GeneratorFunction":s=new Promise((e,o)=>{const n=r(...Array.isArray(t)?[...t]:[]);try{e(n.next().value)}catch(e){o(e)}});break;case"[object Generator]":s=new Promise((e,t)=>{try{e(r.next().value)}catch(e){t(e)}});break;default:s=new Promise((e,t)=>{Promise.resolve(r).then(e).catch(t)})}return Promise.resolve(s).then(e=>[e]).catch(r=>(null==r&&(r=new Error(e)),n instanceof Error?r=n:"string"==typeof n&&(r.message=n),[o,r]))}function ofAnyCase(r,t={}){{const{args:e,defaults:r,error:o,retries:n,timeout:s}={...t};t={args:e,defaults:r,error:o,retries:n,timeout:s}}let o;switch(r.constructor.name||Object.prototype.toString.call(r)){case"Promise":o=r,t.retries=0,delete t.args;break;case"AsyncFunction":o=r(...Array.isArray(t.args)?[...t.args]:[]);break;case"Function":o=new Promise((e,o)=>{try{e(r(...Array.isArray(t.args)?[...t.args]:[]))}catch(e){o(e)}});break;case"GeneratorFunction":o=new Promise((e,o)=>{const n=r(...Array.isArray(t.args)?[...t.args]:[]);try{e(n.next().value)}catch(e){o(e)}});break;case"[object Generator]":o=new Promise((e,t)=>{try{e(r.next().value)}catch(e){t(e)}}),delete t.args;break;default:o=new Promise((e,t)=>{Promise.resolve(r).then(e).catch(t)}),delete t.args}if(void 0!==t.timeout){const e=Number.parseInt(""+t.timeout);Number.isFinite(e)&&e>0?t.timeout=e>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e:delete t.timeout}else delete t.timeout;return(t.timeout?Promise.race([Promise.resolve(o),new Promise((e,r)=>{setTimeout(()=>r(new Error(`Timeout: ${t.timeout}ms`)),t.timeout)})]):Promise.resolve(o)).then(e=>[e]).catch(o=>{if(void 0!==t.retries){const e=Number.parseInt(t.retries);Number.isFinite(e)&&e>0?t.retries=e>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e:delete t.retries}else delete t.retries;return t.retries&&(t.attempt=void 0===t.attempt?0:t.attempt+1,t.attempt0?t.timeout=e>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e:delete t.timeout}else delete t.timeout;return(t.timeout?Promise.race([Promise.resolve(r),new Promise((e,r)=>{setTimeout(()=>r(new Error(`Timeout: ${t.timeout}ms`)),t.timeout)})]):Promise.resolve(r)).then(e=>[e,void 0]).catch(r=>(null==r&&(r=new Error(e)),t.error instanceof Error?r=t.error:"string"==typeof t.error&&(r.message=t.error),[t.defaults,r]))}function ofError(r,t){return Promise.resolve(r).then(()=>{}).catch(r=>(null==r&&(r=new Error(e)),t instanceof Error?r=t:"string"==typeof t&&(r.message=t),r))}function ofIt(r,t,o){return Promise.resolve(r).then(e=>[e]).catch(r=>(null==r&&(r=new Error(e)),o instanceof Error?r=o:"string"==typeof o&&(r.message=o),[t,r]))}function of(r){return Promise.resolve(r).then(e=>[e]).catch(r=>(null==r&&(r=new Error(e)),[void 0,r]))}function ofResult(e,r){return Promise.resolve(e).then(e=>e).catch(()=>r)}function ofSync(r,t,o,n){if(!function isFunction(e){return"[object Function]"===Object.prototype.toString.call(e)&&!/^class\s/.test(Function.prototype.toString.call(e))}(r))return[void 0,new Error(e)];try{return[r(...Array.isArray(t)?[...t]:[]),void 0]}catch(r){let t;return n instanceof Error?t=n:"string"==typeof n?(r.message=n,t=r):t=null==r?new Error(e):r,[o,t]}}function ofOutcome(e,r={}){return new Promise(t=>ofAnyCase(e,r).then(([e,r])=>{t(r||e)}))}class Of{}_defineProperty(Of,"any",ofAny),_defineProperty(Of,"anyCase",ofAnyCase),_defineProperty(Of,"case",ofCase),_defineProperty(Of,"error",ofError),_defineProperty(Of,"it",ofIt),_defineProperty(Of,"async",of),_defineProperty(Of,"result",ofResult),_defineProperty(Of,"sync",ofSync),_defineProperty(Of,"outcome",ofOutcome);export{Of,of,ofAny,ofAnyCase,ofCase,ofError,ofIt,ofOutcome,ofResult,ofSync}; 2 | //# sourceMappingURL=of.mjs.map 3 | -------------------------------------------------------------------------------- /dist/of.cjs: -------------------------------------------------------------------------------- 1 | "use strict";function _defineProperty(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}Object.defineProperty(exports,"__esModule",{value:!0});const e="Unknown Error";function ofAny(r,t,o,n){let s;switch(r.constructor.name||Object.prototype.toString.call(r)){case"Promise":s=r;break;case"AsyncFunction":s=r(...Array.isArray(t)?[...t]:[]);break;case"Function":s=new Promise((e,o)=>{try{e(r(...Array.isArray(t)?[...t]:[]))}catch(e){o(e)}});break;case"GeneratorFunction":s=new Promise((e,o)=>{const n=r(...Array.isArray(t)?[...t]:[]);try{e(n.next().value)}catch(e){o(e)}});break;case"[object Generator]":s=new Promise((e,t)=>{try{e(r.next().value)}catch(e){t(e)}});break;default:s=new Promise((e,t)=>{Promise.resolve(r).then(e).catch(t)})}return Promise.resolve(s).then(e=>[e]).catch(r=>(null==r&&(r=new Error(e)),n instanceof Error?r=n:"string"==typeof n&&(r.message=n),[o,r]))}function ofAnyCase(r,t={}){{const{args:e,defaults:r,error:o,retries:n,timeout:s}={...t};t={args:e,defaults:r,error:o,retries:n,timeout:s}}let o;switch(r.constructor.name||Object.prototype.toString.call(r)){case"Promise":o=r,t.retries=0,delete t.args;break;case"AsyncFunction":o=r(...Array.isArray(t.args)?[...t.args]:[]);break;case"Function":o=new Promise((e,o)=>{try{e(r(...Array.isArray(t.args)?[...t.args]:[]))}catch(e){o(e)}});break;case"GeneratorFunction":o=new Promise((e,o)=>{const n=r(...Array.isArray(t.args)?[...t.args]:[]);try{e(n.next().value)}catch(e){o(e)}});break;case"[object Generator]":o=new Promise((e,t)=>{try{e(r.next().value)}catch(e){t(e)}}),delete t.args;break;default:o=new Promise((e,t)=>{Promise.resolve(r).then(e).catch(t)}),delete t.args}if(void 0!==t.timeout){const e=Number.parseInt(""+t.timeout);Number.isFinite(e)&&e>0?t.timeout=e>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e:delete t.timeout}else delete t.timeout;return(t.timeout?Promise.race([Promise.resolve(o),new Promise((e,r)=>{setTimeout(()=>r(new Error(`Timeout: ${t.timeout}ms`)),t.timeout)})]):Promise.resolve(o)).then(e=>[e]).catch(o=>{if(void 0!==t.retries){const e=Number.parseInt(t.retries);Number.isFinite(e)&&e>0?t.retries=e>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e:delete t.retries}else delete t.retries;return t.retries&&(t.attempt=void 0===t.attempt?0:t.attempt+1,t.attempt0?t.timeout=e>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e:delete t.timeout}else delete t.timeout;return(t.timeout?Promise.race([Promise.resolve(r),new Promise((e,r)=>{setTimeout(()=>r(new Error(`Timeout: ${t.timeout}ms`)),t.timeout)})]):Promise.resolve(r)).then(e=>[e,void 0]).catch(r=>(null==r&&(r=new Error(e)),t.error instanceof Error?r=t.error:"string"==typeof t.error&&(r.message=t.error),[t.defaults,r]))}function ofError(r,t){return Promise.resolve(r).then(()=>{}).catch(r=>(null==r&&(r=new Error(e)),t instanceof Error?r=t:"string"==typeof t&&(r.message=t),r))}function ofIt(r,t,o){return Promise.resolve(r).then(e=>[e]).catch(r=>(null==r&&(r=new Error(e)),o instanceof Error?r=o:"string"==typeof o&&(r.message=o),[t,r]))}function of(r){return Promise.resolve(r).then(e=>[e]).catch(r=>(null==r&&(r=new Error(e)),[void 0,r]))}function ofResult(e,r){return Promise.resolve(e).then(e=>e).catch(()=>r)}function ofSync(r,t,o,n){if(!function isFunction(e){return"[object Function]"===Object.prototype.toString.call(e)&&!/^class\s/.test(Function.prototype.toString.call(e))}(r))return[void 0,new Error(e)];try{return[r(...Array.isArray(t)?[...t]:[]),void 0]}catch(r){let t;return n instanceof Error?t=n:"string"==typeof n?(r.message=n,t=r):t=null==r?new Error(e):r,[o,t]}}function ofOutcome(e,r={}){return new Promise(t=>ofAnyCase(e,r).then(([e,r])=>{t(r||e)}))}class Of{}_defineProperty(Of,"any",ofAny),_defineProperty(Of,"anyCase",ofAnyCase),_defineProperty(Of,"case",ofCase),_defineProperty(Of,"error",ofError),_defineProperty(Of,"it",ofIt),_defineProperty(Of,"async",of),_defineProperty(Of,"result",ofResult),_defineProperty(Of,"sync",ofSync),_defineProperty(Of,"outcome",ofOutcome),exports.Of=Of,exports.of=of,exports.ofAny=ofAny,exports.ofAnyCase=ofAnyCase,exports.ofCase=ofCase,exports.ofError=ofError,exports.ofIt=ofIt,exports.ofOutcome=ofOutcome,exports.ofResult=ofResult,exports.ofSync=ofSync; 2 | //# sourceMappingURL=of.cjs.map 3 | -------------------------------------------------------------------------------- /dist/of.js: -------------------------------------------------------------------------------- 1 | !function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).of={})}(this,(function(e){"use strict";function _defineProperty(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}const r="Unknown Error";function ofAny(e,t,o,n){let s;switch(e.constructor.name||Object.prototype.toString.call(e)){case"Promise":s=e;break;case"AsyncFunction":s=e(...Array.isArray(t)?[...t]:[]);break;case"Function":s=new Promise((r,o)=>{try{r(e(...Array.isArray(t)?[...t]:[]))}catch(e){o(e)}});break;case"GeneratorFunction":s=new Promise((r,o)=>{const n=e(...Array.isArray(t)?[...t]:[]);try{r(n.next().value)}catch(e){o(e)}});break;case"[object Generator]":s=new Promise((r,t)=>{try{r(e.next().value)}catch(e){t(e)}});break;default:s=new Promise((r,t)=>{Promise.resolve(e).then(r).catch(t)})}return Promise.resolve(s).then(e=>[e]).catch(e=>(null==e&&(e=new Error(r)),n instanceof Error?e=n:"string"==typeof n&&(e.message=n),[o,e]))}function ofAnyCase(e,t={}){{const{args:e,defaults:r,error:o,retries:n,timeout:s}={...t};t={args:e,defaults:r,error:o,retries:n,timeout:s}}let o;switch(e.constructor.name||Object.prototype.toString.call(e)){case"Promise":o=e,t.retries=0,delete t.args;break;case"AsyncFunction":o=e(...Array.isArray(t.args)?[...t.args]:[]);break;case"Function":o=new Promise((r,o)=>{try{r(e(...Array.isArray(t.args)?[...t.args]:[]))}catch(e){o(e)}});break;case"GeneratorFunction":o=new Promise((r,o)=>{const n=e(...Array.isArray(t.args)?[...t.args]:[]);try{r(n.next().value)}catch(e){o(e)}});break;case"[object Generator]":o=new Promise((r,t)=>{try{r(e.next().value)}catch(e){t(e)}}),delete t.args;break;default:o=new Promise((r,t)=>{Promise.resolve(e).then(r).catch(t)}),delete t.args}if(void 0!==t.timeout){const e=Number.parseInt(""+t.timeout);Number.isFinite(e)&&e>0?t.timeout=e>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e:delete t.timeout}else delete t.timeout;return(t.timeout?Promise.race([Promise.resolve(o),new Promise((e,r)=>{setTimeout(()=>r(new Error(`Timeout: ${t.timeout}ms`)),t.timeout)})]):Promise.resolve(o)).then(e=>[e]).catch(o=>{if(void 0!==t.retries){const e=Number.parseInt(t.retries);Number.isFinite(e)&&e>0?t.retries=e>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e:delete t.retries}else delete t.retries;return t.retries&&(t.attempt=void 0===t.attempt?0:t.attempt+1,t.attempt0?t.timeout=e>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e:delete t.timeout}else delete t.timeout;return(t.timeout?Promise.race([Promise.resolve(e),new Promise((e,r)=>{setTimeout(()=>r(new Error(`Timeout: ${t.timeout}ms`)),t.timeout)})]):Promise.resolve(e)).then(e=>[e,void 0]).catch(e=>(null==e&&(e=new Error(r)),t.error instanceof Error?e=t.error:"string"==typeof t.error&&(e.message=t.error),[t.defaults,e]))}function ofError(e,t){return Promise.resolve(e).then(()=>{}).catch(e=>(null==e&&(e=new Error(r)),t instanceof Error?e=t:"string"==typeof t&&(e.message=t),e))}function ofIt(e,t,o){return Promise.resolve(e).then(e=>[e]).catch(e=>(null==e&&(e=new Error(r)),o instanceof Error?e=o:"string"==typeof o&&(e.message=o),[t,e]))}function of(e){return Promise.resolve(e).then(e=>[e]).catch(e=>(null==e&&(e=new Error(r)),[void 0,e]))}function ofResult(e,r){return Promise.resolve(e).then(e=>e).catch(()=>r)}function ofSync(e,t,o,n){if(!function isFunction(e){return"[object Function]"===Object.prototype.toString.call(e)&&!/^class\s/.test(Function.prototype.toString.call(e))}(e))return[void 0,new Error(r)];try{return[e(...Array.isArray(t)?[...t]:[]),void 0]}catch(e){let t;return n instanceof Error?t=n:"string"==typeof n?(e.message=n,t=e):t=null==e?new Error(r):e,[o,t]}}function ofOutcome(e,r={}){return new Promise(t=>ofAnyCase(e,r).then(([e,r])=>{t(r||e)}))}class Of{}_defineProperty(Of,"any",ofAny),_defineProperty(Of,"anyCase",ofAnyCase),_defineProperty(Of,"case",ofCase),_defineProperty(Of,"error",ofError),_defineProperty(Of,"it",ofIt),_defineProperty(Of,"async",of),_defineProperty(Of,"result",ofResult),_defineProperty(Of,"sync",ofSync),_defineProperty(Of,"outcome",ofOutcome),e.Of=Of,e.of=of,e.ofAny=ofAny,e.ofAnyCase=ofAnyCase,e.ofCase=ofCase,e.ofError=ofError,e.ofIt=ofIt,e.ofOutcome=ofOutcome,e.ofResult=ofResult,e.ofSync=ofSync,Object.defineProperty(e,"__esModule",{value:!0})})); 2 | //# sourceMappingURL=of.js.map 3 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | OF - Promise wrapper with sugar 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 88 | 93 | 94 | 95 |
96 | 112 | 113 | 114 | 115 | 116 | 121 | 122 | 123 | -------------------------------------------------------------------------------- /test/index.test.js: -------------------------------------------------------------------------------- 1 | const { Of, of, ofAny, ofAnyCase, ofCase, ofError, ofIt, ofOutcome, ofResult, ofSync } = require("../dist/of.cjs"); 2 | 3 | describe("Functions", () => { 4 | it("should not crash on call", () => { 5 | expect(Of).toBeDefined(); 6 | expect(of).toBeDefined(); 7 | expect(ofAny).toBeDefined(); 8 | expect(ofAnyCase).toBeDefined(); 9 | expect(ofCase).toBeDefined(); 10 | expect(ofError).toBeDefined(); 11 | expect(ofIt).toBeDefined(); 12 | expect(ofResult).toBeDefined(); 13 | expect(ofOutcome).toBeDefined(); 14 | }); 15 | it("of", () => { 16 | const value = "Oh, Hi Mark!"; 17 | const promise = new Promise((resolve, reject) => { 18 | resolve(value); 19 | }); 20 | return of(promise).then((result) => { 21 | expect(result[0]).toEqual(value); 22 | expect(result[1]).toBeUndefined(); 23 | }); 24 | }); 25 | it("ofAny", () => { 26 | const value = "Oh, Hi Mark!"; 27 | const promise = new Promise((resolve, reject) => { 28 | resolve(value); 29 | }); 30 | return ofAny(promise).then((result) => { 31 | expect(result[0]).toEqual(value); 32 | expect(result[1]).toBeUndefined(); 33 | }); 34 | }); 35 | it("ofAnyCase", () => { 36 | const value = "Oh, Hi Mark!"; 37 | const promise = new Promise((resolve, reject) => { 38 | resolve(value); 39 | }); 40 | return ofAnyCase(promise).then((result) => { 41 | expect(result[0]).toEqual(value); 42 | expect(result[1]).toBeUndefined(); 43 | }); 44 | }); 45 | it("ofOutcome", () => { 46 | const value = "Oh, Hi Mark!"; 47 | const promise = new Promise((resolve, reject) => { 48 | resolve(value); 49 | }); 50 | return ofOutcome(promise).then((result) => { 51 | expect(result).toEqual(value); 52 | }); 53 | }); 54 | it("ofOutcome - error", () => { 55 | const value = "Oh, Hi Mark!"; 56 | const promise = new Promise((resolve, reject) => { 57 | reject(value); 58 | }); 59 | return ofOutcome(promise).then((result) => { 60 | expect(result).toEqual(value); 61 | }); 62 | }); 63 | it("ofCase", () => { 64 | const value = "Oh, Hi Mark!"; 65 | const promise = new Promise((resolve, reject) => { 66 | resolve(value); 67 | }); 68 | return ofCase(promise).then((result) => { 69 | expect(result[0]).toEqual(value); 70 | expect(result[1]).toBeUndefined(); 71 | }); 72 | }); 73 | it("ofError", () => { 74 | const value = "Oh, Hi Mark!"; 75 | const promise = new Promise((resolve, reject) => { 76 | resolve(value); 77 | }); 78 | return ofError(promise).then((result) => { 79 | expect(result).toBeUndefined(); 80 | }); 81 | }); 82 | it("ofIt", () => { 83 | const value = "Oh, Hi Mark!"; 84 | const promise = new Promise((resolve, reject) => { 85 | resolve(value); 86 | }); 87 | return ofIt(promise).then((result) => { 88 | expect(result[0]).toEqual(value); 89 | expect(result[1]).toBeUndefined(); 90 | }); 91 | }); 92 | it("ofResult", () => { 93 | const value = "Oh, Hi Mark!"; 94 | const promise = new Promise((resolve, reject) => { 95 | resolve(value); 96 | }); 97 | return ofResult(promise).then((result) => { 98 | expect(result).toEqual(value); 99 | }); 100 | }); 101 | it("ofSync", () => { 102 | const value = "Oh, Hi Mark!"; 103 | const callable = (arg) => { 104 | return arg; 105 | }; 106 | expect(ofSync(callable, [value])).toEqual([value, undefined]); 107 | }); 108 | it("Of", () => { 109 | const value = "Oh, Hi Mark!"; 110 | const promise = new Promise((resolve, reject) => { 111 | resolve(value); 112 | }); 113 | return Of.async(promise).then((result) => { 114 | expect(result[0]).toEqual(value); 115 | expect(result[1]).toBeUndefined(); 116 | }); 117 | }); 118 | }); 119 | 120 | describe("Static Methods", () => { 121 | it("Of.async", () => { 122 | const value = "Oh, Hi Mark!"; 123 | const promise = new Promise((resolve, reject) => { 124 | resolve(value); 125 | }); 126 | return Of.async(promise).then((result) => { 127 | expect(result[0]).toEqual(value); 128 | expect(result[1]).toBeUndefined(); 129 | }); 130 | }); 131 | it("Of.any", () => { 132 | const value = "Oh, Hi Mark!"; 133 | const promise = new Promise((resolve, reject) => { 134 | resolve(value); 135 | }); 136 | return Of.any(promise).then((result) => { 137 | expect(result[0]).toEqual(value); 138 | expect(result[1]).toBeUndefined(); 139 | }); 140 | }); 141 | it("Of.anyCase", () => { 142 | const value = "Oh, Hi Mark!"; 143 | const promise = new Promise((resolve, reject) => { 144 | resolve(value); 145 | }); 146 | return Of.anyCase(promise).then((result) => { 147 | expect(result[0]).toEqual(value); 148 | expect(result[1]).toBeUndefined(); 149 | }); 150 | }); 151 | it("Of.outcome", () => { 152 | const value = "Oh, Hi Mark!"; 153 | const promise = new Promise((resolve, reject) => { 154 | resolve(value); 155 | }); 156 | return Of.outcome(promise).then((result) => { 157 | expect(result).toEqual(value); 158 | }); 159 | }); 160 | it("Of.outcome - error", () => { 161 | const value = "Oh, Hi Mark!"; 162 | const promise = new Promise((resolve, reject) => { 163 | reject(value); 164 | }); 165 | return Of.outcome(promise).then((result) => { 166 | expect(result).toEqual(value); 167 | }); 168 | }); 169 | it("Of.case", () => { 170 | const value = "Oh, Hi Mark!"; 171 | const promise = new Promise((resolve, reject) => { 172 | resolve(value); 173 | }); 174 | return Of.case(promise).then((result) => { 175 | expect(result[0]).toEqual(value); 176 | expect(result[1]).toBeUndefined(); 177 | }); 178 | }); 179 | it("Of.error", () => { 180 | const value = "Oh, Hi Mark!"; 181 | const promise = new Promise((resolve, reject) => { 182 | resolve(value); 183 | }); 184 | return Of.error(promise).then((result) => { 185 | expect(result).toBeUndefined(); 186 | }); 187 | }); 188 | it("Of.it", () => { 189 | const value = "Oh, Hi Mark!"; 190 | const promise = new Promise((resolve, reject) => { 191 | resolve(value); 192 | }); 193 | return Of.it(promise).then((result) => { 194 | expect(result[0]).toEqual(value); 195 | expect(result[1]).toBeUndefined(); 196 | }); 197 | }); 198 | it("Of.result", () => { 199 | const value = "Oh, Hi Mark!"; 200 | const promise = new Promise((resolve, reject) => { 201 | resolve(value); 202 | }); 203 | return Of.result(promise).then((result) => { 204 | expect(result).toEqual(value); 205 | }); 206 | }); 207 | it("Of.sync", () => { 208 | const value = "Oh, Hi Mark!"; 209 | const callable = (arg) => { 210 | return arg; 211 | }; 212 | expect(Of.sync(callable, [value])).toEqual([value, undefined]); 213 | }); 214 | }); 215 | -------------------------------------------------------------------------------- /dist/of.d.ts: -------------------------------------------------------------------------------- 1 | export interface IOfConfig { 2 | args?: any[]; 3 | defaults?: any; 4 | error?: string | Error; 5 | retries?: number; 6 | timeout?: number; 7 | } 8 | 9 | /** 10 | * @name of 11 | * @param {Promise} promise 12 | * @returns {Promise<[*, unknown] | [undefined, *]>} 13 | */ 14 | declare function of

(promise: Promise

): Promise<[P | undefined, Error | undefined]>; 15 | 16 | /** 17 | * @name ofAny 18 | * @param {Function|Promise} callable 19 | * @param {[]=} args 20 | * @param {*=} defaultResult 21 | * @param {*=} overrideError 22 | * @returns {Promise<[*, unknown] | [undefined, *]>} 23 | */ 24 | declare function ofAny

( 25 | callable: ((...args: any[]) => P) | Promise

, 26 | args?: any[], 27 | defaultResult?: D, 28 | overrideError?: string | Error, 29 | ): Promise<[P | D | undefined, Error | undefined]>; 30 | 31 | /** 32 | * @name ofAnyCase 33 | * @param {Function|Promise} callable 34 | * @param {*=} config 35 | * @returns {Promise<[*, unknown] | [undefined, *]>} 36 | */ 37 | declare function ofAnyCase

( 38 | callable: ((...args: any[]) => P) | Promise

, 39 | config?: IOfConfig, 40 | ): Promise<[P | any | undefined, Error | undefined]>; 41 | 42 | /** 43 | * @name ofCase 44 | * @param {Promise} promise 45 | * @param {*=} config 46 | * @returns {Promise<[*, unknown] | [undefined, *]>} 47 | */ 48 | declare function ofCase

( 49 | promise: Promise

, 50 | config?: IOfConfig, 51 | ): Promise<[P | any | undefined, Error | undefined]>; 52 | 53 | /** 54 | * @name ofError 55 | * @param {Promise} promise 56 | * @param {*=} overrideError 57 | * @returns {Promise<*>} 58 | */ 59 | declare function ofError

( 60 | promise: Promise

, 61 | overrideError?: string | Error, 62 | ): Promise; 63 | 64 | /** 65 | * @name ofIt 66 | * @param {Promise} promise 67 | * @param {*=} defaultResult 68 | * @param {*=} overrideError 69 | * @returns {Promise<[*, unknown] | [undefined, *]>} 70 | */ 71 | declare function ofIt

( 72 | promise: Promise

, 73 | defaultResult?: D, 74 | overrideError?: string | Error, 75 | ): Promise<[P | D | undefined, Error | undefined]>; 76 | 77 | /** 78 | * @name ofResult 79 | * @param {Promise} promise 80 | * @param {*=} defaultResult 81 | * @returns {Promise<*>} 82 | */ 83 | declare function ofResult

( 84 | promise: Promise

, 85 | defaultResult?: D, 86 | ): Promise<[P | D]>; 87 | 88 | /** 89 | * @name ofSync 90 | * @param {Function} callable 91 | * @param {[]=} args 92 | * @param {*=} defaultResult 93 | * @param {*=} overrideError 94 | * @returns {[*, unknown] | [undefined, *]} 95 | */ 96 | declare function ofSync( 97 | callable: (...args: any[]) => R, 98 | args?: any[], 99 | defaultResult?: D, 100 | overrideError?: string | Error, 101 | ): [R | undefined, Error | undefined]; 102 | 103 | /** 104 | * @name ofOutcome 105 | * @param {Function|Promise} callable 106 | * @param {*=} config 107 | * @returns {Promise<[*, unknown] | [undefined, *]>} 108 | */ 109 | declare function ofOutcome

( 110 | callable: ((...args: any[]) => P) | Promise

, 111 | config?: IOfConfig, 112 | ): Promise

; 113 | 114 | declare class Of { 115 | /** 116 | * @name any 117 | * @alias ofAny 118 | * @public 119 | * @static 120 | * @method 121 | * @param {Function|Promise} callable 122 | * @param {[]=} args 123 | * @param {*=} defaultResult 124 | * @param {*=} overrideError 125 | * @returns {Promise<[*, unknown] | [undefined, *]>} 126 | */ 127 | public static any

( 128 | callable: ((...args: any[]) => P) | Promise

, 129 | args?: any[], 130 | defaultResult?: D, 131 | overrideError?: string | Error, 132 | ): Promise<[P | D | undefined, Error | undefined]>; 133 | /** 134 | * @name anyCase 135 | * @alias ofAnyCase 136 | * @public 137 | * @static 138 | * @method 139 | * @param {Function|Promise} callable 140 | * @param {*=} config 141 | * @returns {Promise<[*, unknown] | [undefined, *]>} 142 | */ 143 | public static anyCase

( 144 | callable: ((...args: any[]) => P) | Promise

, 145 | config?: IOfConfig, 146 | ): Promise<[P | any | undefined, Error | undefined]>; 147 | /** 148 | * @name case 149 | * @alias ofCase 150 | * @public 151 | * @static 152 | * @method 153 | * @param {Promise} promise 154 | * @param {*=} config 155 | * @returns {Promise<[*, unknown] | [undefined, *]>} 156 | */ 157 | public static case

( 158 | promise: Promise

, 159 | config?: IOfConfig, 160 | ): Promise<[P | any | undefined, Error | undefined]>; 161 | /** 162 | * @name error 163 | * @alias ofError 164 | * @public 165 | * @static 166 | * @method 167 | * @param {Promise} promise 168 | * @param {*=} overrideError 169 | * @returns {Promise<*>} 170 | */ 171 | public static error

( 172 | promise: Promise

, 173 | overrideError?: string | Error, 174 | ): Promise; 175 | /** 176 | * @name it 177 | * @alias ofIt 178 | * @public 179 | * @static 180 | * @method 181 | * @param {Promise} promise 182 | * @param {*=} defaultResult 183 | * @param {*=} overrideError 184 | * @returns {Promise<[*, unknown] | [undefined, *]>} 185 | */ 186 | public static it

( 187 | promise: Promise

, 188 | defaultResult?: D, 189 | overrideError?: string | Error, 190 | ): Promise<[P | D | undefined, Error | undefined]>; 191 | /** 192 | * @name async 193 | * @alias of 194 | * @public 195 | * @static 196 | * @method 197 | * @param {Promise} promise 198 | * @returns {Promise<[*, unknown] | [undefined, *]>} 199 | */ 200 | public static async

(promise: Promise

): Promise<[P | undefined, Error | undefined]>; 201 | /** 202 | * @name result 203 | * @alias ofResult 204 | * @public 205 | * @static 206 | * @method 207 | * @param {Promise} promise 208 | * @param {*=} defaultResult 209 | * @returns {Promise<*>} 210 | */ 211 | public static result

( 212 | promise: Promise

, 213 | defaultResult?: D, 214 | ): Promise<[P | D]>; 215 | /** 216 | * @name sync 217 | * @alias ofSync 218 | * @public 219 | * @static 220 | * @method 221 | * @param {Function} callable 222 | * @param {[]=} args 223 | * @param {*=} defaultResult 224 | * @param {*=} overrideError 225 | * @returns {[*, unknown] | [undefined, *]} 226 | */ 227 | public static sync( 228 | callable: (...args: any[]) => R, 229 | args?: any[], 230 | defaultResult?: D, 231 | overrideError?: string | Error, 232 | ): [R | undefined, Error | undefined]; 233 | /** 234 | * @name outcome 235 | * @alias ofOutcome 236 | * @public 237 | * @static 238 | * @method 239 | * @param {Function|Promise} callable 240 | * @param {*=} config 241 | * @returns {Promise<[*, unknown] | [undefined, *]>} 242 | */ 243 | public static outcome

( 244 | callable: ((...args: any[]) => P) | Promise

, 245 | config?: IOfConfig, 246 | ): Promise

; 247 | } 248 | 249 | export { Of, of, ofAny, ofAnyCase, ofCase, ofError, ofIt, ofOutcome, ofResult, ofSync }; 250 | -------------------------------------------------------------------------------- /dist/of.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"of.js","sources":["../src/const/error.js","../src/core/ofAny.js","../src/const/type.js","../src/core/ofAnyCase.js","../src/core/ofCase.js","../src/core/ofError.js","../src/core/ofIt.js","../src/core/of.js","../src/core/ofResult.js","../src/core/ofSync.js","../src/util/isFunction.js","../src/core/ofOutcome.js","../src/class/Of.js"],"sourcesContent":["export const ERR_UNKNOWN = \"Unknown Error\";\n","import { ERR_UNKNOWN } from \"../const/error.js\";\nimport { FUNC, FUNC_ASYNC, FUNC_GEN, OBJ_GEN, PROMISE } from \"../const/type.js\";\n\n/**\n * @name ofAny\n * @param {Function|Promise} callable\n * @param {[]=} args\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function ofAny(callable, args, defaultResult, overrideError) {\n let call;\n switch (callable.constructor.name || Object.prototype.toString.call(callable)) {\n case PROMISE:\n call = callable;\n break;\n case FUNC_ASYNC:\n call = callable(...(Array.isArray(args) ? [...args] : []));\n break;\n case FUNC:\n call = new Promise((resolve, reject) => {\n try {\n resolve(callable(...(Array.isArray(args) ? [...args] : [])));\n } catch (caughtFunctionError) {\n reject(caughtFunctionError);\n }\n });\n break;\n case FUNC_GEN:\n call = new Promise((resolve, reject) => {\n const gen = callable(...(Array.isArray(args) ? [...args] : []));\n try {\n resolve(gen.next().value);\n } catch (caughtGeneratorFunctionError) {\n reject(caughtGeneratorFunctionError);\n }\n });\n break;\n case OBJ_GEN:\n call = new Promise((resolve, reject) => {\n try {\n resolve(callable.next().value);\n } catch (caughtGeneratorError) {\n reject(caughtGeneratorError);\n }\n });\n break;\n default:\n call = new Promise((resolve, reject) => {\n Promise.resolve(callable).then(resolve).catch(reject);\n });\n }\n return Promise.resolve(call)\n .then((result) => [result])\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (overrideError instanceof Error) {\n caughtError = overrideError;\n } else if (typeof overrideError === \"string\") {\n caughtError.message = overrideError;\n }\n return [defaultResult, caughtError];\n });\n}\n","export const FUNC = \"Function\";\nexport const FUNC_ASYNC = \"AsyncFunction\";\nexport const FUNC_GEN = \"GeneratorFunction\";\nexport const OBJ_GEN = \"[object Generator]\";\nexport const PROMISE = \"Promise\";\n","import { ERR_UNKNOWN } from \"../const/error.js\";\nimport { FUNC, FUNC_ASYNC, FUNC_GEN, OBJ_GEN, PROMISE } from \"../const/type.js\";\n\n/**\n * @name ofAnyCase\n * @param {Function|Promise} callable\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function ofAnyCase(callable, config = {}) {\n {\n const { args, defaults, error, retries, timeout } = { ...config };\n config = { args, defaults, error, retries, timeout };\n }\n let call;\n switch (callable.constructor.name || Object.prototype.toString.call(callable)) {\n case PROMISE:\n call = callable;\n config.retries = 0;\n delete config.args;\n break;\n case FUNC_ASYNC:\n call = callable(...(Array.isArray(config.args) ? [...config.args] : []));\n break;\n case FUNC:\n call = new Promise((resolve, reject) => {\n try {\n resolve(callable(...(Array.isArray(config.args) ? [...config.args] : [])));\n } catch (caughtFunctionError) {\n reject(caughtFunctionError);\n }\n });\n break;\n case FUNC_GEN:\n call = new Promise((resolve, reject) => {\n const gen = callable(...(Array.isArray(config.args) ? [...config.args] : []));\n try {\n resolve(gen.next().value);\n } catch (caughtGeneratorFunctionError) {\n reject(caughtGeneratorFunctionError);\n }\n });\n break;\n case OBJ_GEN:\n call = new Promise((resolve, reject) => {\n try {\n resolve(callable.next().value);\n } catch (caughtGeneratorError) {\n reject(caughtGeneratorError);\n }\n });\n delete config.args;\n break;\n default:\n call = new Promise((resolve, reject) => {\n Promise.resolve(callable).then(resolve).catch(reject);\n });\n delete config.args;\n }\n if (config.timeout !== undefined) {\n const timeout = Number.parseInt(`${config.timeout}`);\n if (Number.isFinite(timeout) && timeout > 0) {\n config.timeout = timeout > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : timeout;\n } else {\n delete config.timeout;\n }\n } else {\n delete config.timeout;\n }\n return (config.timeout\n ? Promise.race([\n Promise.resolve(call),\n new Promise((_resolve, reject) => {\n setTimeout(() => reject(new Error(`Timeout: ${config.timeout}ms`)), config.timeout);\n }),\n ])\n : Promise.resolve(call)\n )\n .then((result) => [result])\n .catch((caughtError) => {\n if (config.retries !== undefined) {\n const retries = Number.parseInt(config.retries);\n if (Number.isFinite(retries) && retries > 0) {\n config.retries = retries > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : retries;\n } else {\n delete config.retries;\n }\n } else {\n delete config.retries;\n }\n if (config.retries) {\n config.attempt = config.attempt === undefined ? 0 : config.attempt + 1;\n if (config.attempt < config.retries) {\n return ofAnyCase(callable, config);\n }\n }\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (config.error instanceof Error) {\n caughtError = config.error;\n } else if (typeof config.error === \"string\") {\n caughtError.message = config.error;\n }\n return [config.defaults, caughtError];\n });\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\n/**\n * @name ofCase\n * @param {Promise} promise\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function ofCase(promise, config = {}) {\n {\n const { args, defaults, error, timeout } = { ...config };\n config = { args, defaults, error, timeout };\n }\n if (config.timeout !== undefined) {\n const timeout = Number.parseInt(`${config.timeout}`);\n if (Number.isFinite(timeout) && timeout > 0) {\n config.timeout = timeout > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : timeout;\n } else {\n delete config.timeout;\n }\n } else {\n delete config.timeout;\n }\n return (config.timeout\n ? Promise.race([\n Promise.resolve(promise),\n new Promise((_resolve, reject) => {\n setTimeout(() => reject(new Error(`Timeout: ${config.timeout}ms`)), config.timeout);\n }),\n ])\n : Promise.resolve(promise)\n )\n .then((result) => [result, undefined])\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (config.error instanceof Error) {\n caughtError = config.error;\n } else if (typeof config.error === \"string\") {\n caughtError.message = config.error;\n }\n return [config.defaults, caughtError];\n });\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\n/**\n * @name ofError\n * @param {Promise} promise\n * @param {*=} overrideError\n * @returns {Promise<*>}\n */\nexport function ofError(promise, overrideError) {\n return Promise.resolve(promise)\n .then(() => undefined)\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (overrideError instanceof Error) {\n caughtError = overrideError;\n } else if (typeof overrideError === \"string\") {\n caughtError.message = overrideError;\n }\n return caughtError;\n });\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\n/**\n * @name ofIt\n * @param {Promise} promise\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function ofIt(promise, defaultResult, overrideError) {\n return Promise.resolve(promise)\n .then((result) => [result])\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (overrideError instanceof Error) {\n caughtError = overrideError;\n } else if (typeof overrideError === \"string\") {\n caughtError.message = overrideError;\n }\n return [defaultResult, caughtError];\n });\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\n/**\n * @name of\n * @param {Promise} promise\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function of(promise) {\n return Promise.resolve(promise)\n .then((result) => [result])\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n return [undefined, caughtError];\n });\n}\n","/**\n * @name ofResult\n * @param {Promise} promise\n * @param {*=} defaultResult\n * @returns {Promise<*>}\n */\nexport function ofResult(promise, defaultResult) {\n return Promise.resolve(promise)\n .then((result) => result)\n .catch(() => defaultResult);\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\nimport { isFunction } from \"../util/isFunction.js\";\n\n/**\n * @name ofSync\n * @param {Function} callable\n * @param {[]=} args\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {[*, unknown] | [undefined, *]}\n */\nexport function ofSync(callable, args, defaultResult, overrideError) {\n if (!isFunction(callable)) {\n return [undefined, new Error(ERR_UNKNOWN)];\n }\n try {\n return [callable(...(Array.isArray(args) ? [...args] : [])), undefined];\n } catch (caughtFunctionError) {\n let caughtError;\n if (overrideError instanceof Error) {\n caughtError = overrideError;\n } else if (typeof overrideError === \"string\") {\n caughtFunctionError.message = overrideError;\n caughtError = caughtFunctionError;\n } else if (caughtFunctionError === undefined || caughtFunctionError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n } else {\n caughtError = caughtFunctionError;\n }\n return [defaultResult, caughtError];\n }\n}\n","/**\n * @param {*} value\n * @returns {boolean}\n */\nexport function isFunction(value) {\n if (Object.prototype.toString.call(value) !== \"[object Function]\") {\n return false;\n }\n return !/^class\\s/.test(Function.prototype.toString.call(value));\n}\n","import { ofAnyCase } from \"./ofAnyCase.js\";\n\n/**\n * @name ofOutcome\n * @description Returns result or thrown error wherever happens\n * @param {Function|Promise} callable\n * @param {*=} config\n * @returns {Promise<*>}\n */\nexport function ofOutcome(callable, config = {}) {\n return new Promise((resolve) =>\n ofAnyCase(callable, config).then(([result, error]) => {\n resolve(error ? error : result);\n }),\n );\n}\n","import { ofAny } from \"../core/ofAny.js\";\nimport { ofAnyCase } from \"../core/ofAnyCase.js\";\nimport { ofCase } from \"../core/ofCase.js\";\nimport { ofError } from \"../core/ofError.js\";\nimport { ofIt } from \"../core/ofIt.js\";\nimport { of } from \"../core/of.js\";\nimport { ofResult } from \"../core/ofResult.js\";\nimport { ofSync } from \"../core/ofSync.js\";\nimport { ofOutcome } from \"../core/ofOutcome.js\";\n\nexport class Of {\n /**\n * @name any\n * @alias ofAny\n * @public\n * @static\n * @method\n * @param {Function|Promise} callable\n * @param {[]=} args\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static any = ofAny;\n /**\n * @name anyCase\n * @alias ofAnyCase\n * @public\n * @static\n * @method\n * @param {Function|Promise} callable\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static anyCase = ofAnyCase;\n /**\n * @name case\n * @alias ofCase\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static case = ofCase;\n /**\n * @name error\n * @alias ofError\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @param {*=} overrideError\n * @returns {Promise<*>}\n */\n static error = ofError;\n /**\n * @name it\n * @alias ofIt\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static it = ofIt;\n /**\n * @name async\n * @alias of\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static async = of;\n /**\n * @name result\n * @alias ofResult\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @param {*=} defaultResult\n * @returns {Promise<*>}\n */\n static result = ofResult;\n /**\n * @name sync\n * @alias ofSync\n * @public\n * @static\n * @method\n * @param {Function} callable\n * @param {[]=} args\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {[*, unknown] | [undefined, *]}\n */\n static sync = ofSync;\n /**\n * @name outcome\n * @alias ofOutcome\n * @public\n * @static\n * @method\n * @param {Function|Promise} callable\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static outcome = ofOutcome;\n}\n"],"names":["ERR_UNKNOWN","ofAny","callable","args","defaultResult","overrideError","call","constructor","name","Object","prototype","toString","Array","isArray","Promise","resolve","reject","caughtFunctionError","gen","next","value","caughtGeneratorFunctionError","caughtGeneratorError","then","catch","result","caughtError","Error","message","ofAnyCase","config","defaults","error","retries","timeout","undefined","Number","parseInt","isFinite","MAX_SAFE_INTEGER","race","_resolve","setTimeout","attempt","ofCase","promise","ofError","ofIt","of","ofResult","ofSync","isFunction","test","Function","ofOutcome","Of"],"mappings":"gXAAO,MAAMA,EAAc,gBCWpB,SAASC,MAAMC,EAAUC,EAAMC,EAAeC,OAC/CC,SACIJ,EAASK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2BAxBN0B,UAmCGX,wBAnCHW,WA8CIT,yBA9CJS,QA0DCR,sBA1DDQ,WAoEIP,oBApEJO,YA+EKN,0BA/ELM,UA4FGL,wBA5FHK,aAuGMD"} -------------------------------------------------------------------------------- /dist/of.cjs.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"of.cjs","sources":["../src/const/error.js","../src/core/ofAny.js","../src/const/type.js","../src/core/ofAnyCase.js","../src/core/ofCase.js","../src/core/ofError.js","../src/core/ofIt.js","../src/core/of.js","../src/core/ofResult.js","../src/core/ofSync.js","../src/util/isFunction.js","../src/core/ofOutcome.js","../src/class/Of.js"],"sourcesContent":["export const ERR_UNKNOWN = \"Unknown Error\";\n","import { ERR_UNKNOWN } from \"../const/error.js\";\nimport { FUNC, FUNC_ASYNC, FUNC_GEN, OBJ_GEN, PROMISE } from \"../const/type.js\";\n\n/**\n * @name ofAny\n * @param {Function|Promise} callable\n * @param {[]=} args\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function ofAny(callable, args, defaultResult, overrideError) {\n let call;\n switch (callable.constructor.name || Object.prototype.toString.call(callable)) {\n case PROMISE:\n call = callable;\n break;\n case FUNC_ASYNC:\n call = callable(...(Array.isArray(args) ? [...args] : []));\n break;\n case FUNC:\n call = new Promise((resolve, reject) => {\n try {\n resolve(callable(...(Array.isArray(args) ? [...args] : [])));\n } catch (caughtFunctionError) {\n reject(caughtFunctionError);\n }\n });\n break;\n case FUNC_GEN:\n call = new Promise((resolve, reject) => {\n const gen = callable(...(Array.isArray(args) ? [...args] : []));\n try {\n resolve(gen.next().value);\n } catch (caughtGeneratorFunctionError) {\n reject(caughtGeneratorFunctionError);\n }\n });\n break;\n case OBJ_GEN:\n call = new Promise((resolve, reject) => {\n try {\n resolve(callable.next().value);\n } catch (caughtGeneratorError) {\n reject(caughtGeneratorError);\n }\n });\n break;\n default:\n call = new Promise((resolve, reject) => {\n Promise.resolve(callable).then(resolve).catch(reject);\n });\n }\n return Promise.resolve(call)\n .then((result) => [result])\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (overrideError instanceof Error) {\n caughtError = overrideError;\n } else if (typeof overrideError === \"string\") {\n caughtError.message = overrideError;\n }\n return [defaultResult, caughtError];\n });\n}\n","export const FUNC = \"Function\";\nexport const FUNC_ASYNC = \"AsyncFunction\";\nexport const FUNC_GEN = \"GeneratorFunction\";\nexport const OBJ_GEN = \"[object Generator]\";\nexport const PROMISE = \"Promise\";\n","import { ERR_UNKNOWN } from \"../const/error.js\";\nimport { FUNC, FUNC_ASYNC, FUNC_GEN, OBJ_GEN, PROMISE } from \"../const/type.js\";\n\n/**\n * @name ofAnyCase\n * @param {Function|Promise} callable\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function ofAnyCase(callable, config = {}) {\n {\n const { args, defaults, error, retries, timeout } = { ...config };\n config = { args, defaults, error, retries, timeout };\n }\n let call;\n switch (callable.constructor.name || Object.prototype.toString.call(callable)) {\n case PROMISE:\n call = callable;\n config.retries = 0;\n delete config.args;\n break;\n case FUNC_ASYNC:\n call = callable(...(Array.isArray(config.args) ? [...config.args] : []));\n break;\n case FUNC:\n call = new Promise((resolve, reject) => {\n try {\n resolve(callable(...(Array.isArray(config.args) ? [...config.args] : [])));\n } catch (caughtFunctionError) {\n reject(caughtFunctionError);\n }\n });\n break;\n case FUNC_GEN:\n call = new Promise((resolve, reject) => {\n const gen = callable(...(Array.isArray(config.args) ? [...config.args] : []));\n try {\n resolve(gen.next().value);\n } catch (caughtGeneratorFunctionError) {\n reject(caughtGeneratorFunctionError);\n }\n });\n break;\n case OBJ_GEN:\n call = new Promise((resolve, reject) => {\n try {\n resolve(callable.next().value);\n } catch (caughtGeneratorError) {\n reject(caughtGeneratorError);\n }\n });\n delete config.args;\n break;\n default:\n call = new Promise((resolve, reject) => {\n Promise.resolve(callable).then(resolve).catch(reject);\n });\n delete config.args;\n }\n if (config.timeout !== undefined) {\n const timeout = Number.parseInt(`${config.timeout}`);\n if (Number.isFinite(timeout) && timeout > 0) {\n config.timeout = timeout > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : timeout;\n } else {\n delete config.timeout;\n }\n } else {\n delete config.timeout;\n }\n return (config.timeout\n ? Promise.race([\n Promise.resolve(call),\n new Promise((_resolve, reject) => {\n setTimeout(() => reject(new Error(`Timeout: ${config.timeout}ms`)), config.timeout);\n }),\n ])\n : Promise.resolve(call)\n )\n .then((result) => [result])\n .catch((caughtError) => {\n if (config.retries !== undefined) {\n const retries = Number.parseInt(config.retries);\n if (Number.isFinite(retries) && retries > 0) {\n config.retries = retries > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : retries;\n } else {\n delete config.retries;\n }\n } else {\n delete config.retries;\n }\n if (config.retries) {\n config.attempt = config.attempt === undefined ? 0 : config.attempt + 1;\n if (config.attempt < config.retries) {\n return ofAnyCase(callable, config);\n }\n }\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (config.error instanceof Error) {\n caughtError = config.error;\n } else if (typeof config.error === \"string\") {\n caughtError.message = config.error;\n }\n return [config.defaults, caughtError];\n });\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\n/**\n * @name ofCase\n * @param {Promise} promise\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function ofCase(promise, config = {}) {\n {\n const { args, defaults, error, timeout } = { ...config };\n config = { args, defaults, error, timeout };\n }\n if (config.timeout !== undefined) {\n const timeout = Number.parseInt(`${config.timeout}`);\n if (Number.isFinite(timeout) && timeout > 0) {\n config.timeout = timeout > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : timeout;\n } else {\n delete config.timeout;\n }\n } else {\n delete config.timeout;\n }\n return (config.timeout\n ? Promise.race([\n Promise.resolve(promise),\n new Promise((_resolve, reject) => {\n setTimeout(() => reject(new Error(`Timeout: ${config.timeout}ms`)), config.timeout);\n }),\n ])\n : Promise.resolve(promise)\n )\n .then((result) => [result, undefined])\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (config.error instanceof Error) {\n caughtError = config.error;\n } else if (typeof config.error === \"string\") {\n caughtError.message = config.error;\n }\n return [config.defaults, caughtError];\n });\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\n/**\n * @name ofError\n * @param {Promise} promise\n * @param {*=} overrideError\n * @returns {Promise<*>}\n */\nexport function ofError(promise, overrideError) {\n return Promise.resolve(promise)\n .then(() => undefined)\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (overrideError instanceof Error) {\n caughtError = overrideError;\n } else if (typeof overrideError === \"string\") {\n caughtError.message = overrideError;\n }\n return caughtError;\n });\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\n/**\n * @name ofIt\n * @param {Promise} promise\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function ofIt(promise, defaultResult, overrideError) {\n return Promise.resolve(promise)\n .then((result) => [result])\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (overrideError instanceof Error) {\n caughtError = overrideError;\n } else if (typeof overrideError === \"string\") {\n caughtError.message = overrideError;\n }\n return [defaultResult, caughtError];\n });\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\n/**\n * @name of\n * @param {Promise} promise\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function of(promise) {\n return Promise.resolve(promise)\n .then((result) => [result])\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n return [undefined, caughtError];\n });\n}\n","/**\n * @name ofResult\n * @param {Promise} promise\n * @param {*=} defaultResult\n * @returns {Promise<*>}\n */\nexport function ofResult(promise, defaultResult) {\n return Promise.resolve(promise)\n .then((result) => result)\n .catch(() => defaultResult);\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\nimport { isFunction } from \"../util/isFunction.js\";\n\n/**\n * @name ofSync\n * @param {Function} callable\n * @param {[]=} args\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {[*, unknown] | [undefined, *]}\n */\nexport function ofSync(callable, args, defaultResult, overrideError) {\n if (!isFunction(callable)) {\n return [undefined, new Error(ERR_UNKNOWN)];\n }\n try {\n return [callable(...(Array.isArray(args) ? [...args] : [])), undefined];\n } catch (caughtFunctionError) {\n let caughtError;\n if (overrideError instanceof Error) {\n caughtError = overrideError;\n } else if (typeof overrideError === \"string\") {\n caughtFunctionError.message = overrideError;\n caughtError = caughtFunctionError;\n } else if (caughtFunctionError === undefined || caughtFunctionError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n } else {\n caughtError = caughtFunctionError;\n }\n return [defaultResult, caughtError];\n }\n}\n","/**\n * @param {*} value\n * @returns {boolean}\n */\nexport function isFunction(value) {\n if (Object.prototype.toString.call(value) !== \"[object Function]\") {\n return false;\n }\n return !/^class\\s/.test(Function.prototype.toString.call(value));\n}\n","import { ofAnyCase } from \"./ofAnyCase.js\";\n\n/**\n * @name ofOutcome\n * @description Returns result or thrown error wherever happens\n * @param {Function|Promise} callable\n * @param {*=} config\n * @returns {Promise<*>}\n */\nexport function ofOutcome(callable, config = {}) {\n return new Promise((resolve) =>\n ofAnyCase(callable, config).then(([result, error]) => {\n resolve(error ? error : result);\n }),\n );\n}\n","import { ofAny } from \"../core/ofAny.js\";\nimport { ofAnyCase } from \"../core/ofAnyCase.js\";\nimport { ofCase } from \"../core/ofCase.js\";\nimport { ofError } from \"../core/ofError.js\";\nimport { ofIt } from \"../core/ofIt.js\";\nimport { of } from \"../core/of.js\";\nimport { ofResult } from \"../core/ofResult.js\";\nimport { ofSync } from \"../core/ofSync.js\";\nimport { ofOutcome } from \"../core/ofOutcome.js\";\n\nexport class Of {\n /**\n * @name any\n * @alias ofAny\n * @public\n * @static\n * @method\n * @param {Function|Promise} callable\n * @param {[]=} args\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static any = ofAny;\n /**\n * @name anyCase\n * @alias ofAnyCase\n * @public\n * @static\n * @method\n * @param {Function|Promise} callable\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static anyCase = ofAnyCase;\n /**\n * @name case\n * @alias ofCase\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static case = ofCase;\n /**\n * @name error\n * @alias ofError\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @param {*=} overrideError\n * @returns {Promise<*>}\n */\n static error = ofError;\n /**\n * @name it\n * @alias ofIt\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static it = ofIt;\n /**\n * @name async\n * @alias of\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static async = of;\n /**\n * @name result\n * @alias ofResult\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @param {*=} defaultResult\n * @returns {Promise<*>}\n */\n static result = ofResult;\n /**\n * @name sync\n * @alias ofSync\n * @public\n * @static\n * @method\n * @param {Function} callable\n * @param {[]=} args\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {[*, unknown] | [undefined, *]}\n */\n static sync = ofSync;\n /**\n * @name outcome\n * @alias ofOutcome\n * @public\n * @static\n * @method\n * @param {Function|Promise} callable\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static outcome = ofOutcome;\n}\n"],"names":["ERR_UNKNOWN","ofAny","callable","args","defaultResult","overrideError","call","constructor","name","Object","prototype","toString","Array","isArray","Promise","resolve","reject","caughtFunctionError","gen","next","value","caughtGeneratorFunctionError","caughtGeneratorError","then","catch","result","caughtError","Error","message","ofAnyCase","config","defaults","error","retries","timeout","undefined","Number","parseInt","isFinite","MAX_SAFE_INTEGER","race","_resolve","setTimeout","attempt","ofCase","promise","ofError","ofIt","of","ofResult","ofSync","isFunction","test","Function","ofOutcome","Of"],"mappings":"0MAAO,MAAMA,EAAc,gBCWpB,SAASC,MAAMC,EAAUC,EAAMC,EAAeC,OAC/CC,SACIJ,EAASK,YAAYC,MAAQC,OAAOC,UAAUC,SAASL,KAAKJ,QCT/C,UDWjBI,EAAOJ,YCda,gBDiBpBI,EAAOJ,KAAaU,MAAMC,QAAQV,GAAQ,IAAIA,GAAQ,cClBxC,WDqBdG,EAAO,IAAIQ,QAAQ,CAACC,EAASC,SAEzBD,EAAQb,KAAaU,MAAMC,QAAQV,GAAQ,IAAIA,GAAQ,KACvD,MAAOc,GACPD,EAAOC,gBCvBO,oBD4BlBX,EAAO,IAAIQ,QAAQ,CAACC,EAASC,WACrBE,EAAMhB,KAAaU,MAAMC,QAAQV,GAAQ,IAAIA,GAAQ,QAEzDY,EAAQG,EAAIC,OAAOC,OACnB,MAAOC,GACPL,EAAOK,gBChCM,qBDqCjBf,EAAO,IAAIQ,QAAQ,CAACC,EAASC,SAEzBD,EAAQb,EAASiB,OAAOC,OACxB,MAAOE,GACPN,EAAOM,oBAKXhB,EAAO,IAAIQ,QAAQ,CAACC,EAASC,KAC3BF,QAAQC,QAAQb,GAAUqB,KAAKR,GAASS,MAAMR,YAG7CF,QAAQC,QAAQT,GACpBiB,KAAME,GAAW,CAACA,IAClBD,MAAOE,IACFA,MAAAA,IACFA,EAAc,IAAIC,MAAM3B,IAEtBK,aAAyBsB,MAC3BD,EAAcrB,EACoB,iBAAlBA,IAChBqB,EAAYE,QAAUvB,GAEjB,CAACD,EAAesB,KEvDtB,SAASG,UAAU3B,EAAU4B,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D,MAAOlB,OACHS,SACArB,aAAyBsB,MAC3BD,EAAcrB,EACoB,iBAAlBA,GAChBY,EAAoBW,QAAUvB,EAC9BqB,EAAcT,GAEdS,EADST,MAAAA,EACK,IAAIU,MAAM3B,GAEViB,EAET,CAACb,EAAesB,IErBpB,SAAS4B,UAAUpD,EAAU4B,EAAS,WACpC,IAAIhB,QAASC,GAClBc,UAAU3B,EAAU4B,GAAQP,KAAK,EAAEE,EAAQO,MACzCjB,EAAQiB,GAAgBP,MCFvB,MAAM8B,oBAAAA,SAaEtD,uBAbFsD,aAwBM1B,2BAxBN0B,UAmCGX,wBAnCHW,WA8CIT,yBA9CJS,QA0DCR,sBA1DDQ,WAoEIP,oBApEJO,YA+EKN,0BA/ELM,UA4FGL,wBA5FHK,aAuGMD"} -------------------------------------------------------------------------------- /dist/of.mjs.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"of.mjs","sources":["../src/const/error.js","../src/core/ofAny.js","../src/const/type.js","../src/core/ofAnyCase.js","../src/core/ofCase.js","../src/core/ofError.js","../src/core/ofIt.js","../src/core/of.js","../src/core/ofResult.js","../src/core/ofSync.js","../src/util/isFunction.js","../src/core/ofOutcome.js","../src/class/Of.js"],"sourcesContent":["export const ERR_UNKNOWN = \"Unknown Error\";\n","import { ERR_UNKNOWN } from \"../const/error.js\";\nimport { FUNC, FUNC_ASYNC, FUNC_GEN, OBJ_GEN, PROMISE } from \"../const/type.js\";\n\n/**\n * @name ofAny\n * @param {Function|Promise} callable\n * @param {[]=} args\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function ofAny(callable, args, defaultResult, overrideError) {\n let call;\n switch (callable.constructor.name || Object.prototype.toString.call(callable)) {\n case PROMISE:\n call = callable;\n break;\n case FUNC_ASYNC:\n call = callable(...(Array.isArray(args) ? [...args] : []));\n break;\n case FUNC:\n call = new Promise((resolve, reject) => {\n try {\n resolve(callable(...(Array.isArray(args) ? [...args] : [])));\n } catch (caughtFunctionError) {\n reject(caughtFunctionError);\n }\n });\n break;\n case FUNC_GEN:\n call = new Promise((resolve, reject) => {\n const gen = callable(...(Array.isArray(args) ? [...args] : []));\n try {\n resolve(gen.next().value);\n } catch (caughtGeneratorFunctionError) {\n reject(caughtGeneratorFunctionError);\n }\n });\n break;\n case OBJ_GEN:\n call = new Promise((resolve, reject) => {\n try {\n resolve(callable.next().value);\n } catch (caughtGeneratorError) {\n reject(caughtGeneratorError);\n }\n });\n break;\n default:\n call = new Promise((resolve, reject) => {\n Promise.resolve(callable).then(resolve).catch(reject);\n });\n }\n return Promise.resolve(call)\n .then((result) => [result])\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (overrideError instanceof Error) {\n caughtError = overrideError;\n } else if (typeof overrideError === \"string\") {\n caughtError.message = overrideError;\n }\n return [defaultResult, caughtError];\n });\n}\n","export const FUNC = \"Function\";\nexport const FUNC_ASYNC = \"AsyncFunction\";\nexport const FUNC_GEN = \"GeneratorFunction\";\nexport const OBJ_GEN = \"[object Generator]\";\nexport const PROMISE = \"Promise\";\n","import { ERR_UNKNOWN } from \"../const/error.js\";\nimport { FUNC, FUNC_ASYNC, FUNC_GEN, OBJ_GEN, PROMISE } from \"../const/type.js\";\n\n/**\n * @name ofAnyCase\n * @param {Function|Promise} callable\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function ofAnyCase(callable, config = {}) {\n {\n const { args, defaults, error, retries, timeout } = { ...config };\n config = { args, defaults, error, retries, timeout };\n }\n let call;\n switch (callable.constructor.name || Object.prototype.toString.call(callable)) {\n case PROMISE:\n call = callable;\n config.retries = 0;\n delete config.args;\n break;\n case FUNC_ASYNC:\n call = callable(...(Array.isArray(config.args) ? [...config.args] : []));\n break;\n case FUNC:\n call = new Promise((resolve, reject) => {\n try {\n resolve(callable(...(Array.isArray(config.args) ? [...config.args] : [])));\n } catch (caughtFunctionError) {\n reject(caughtFunctionError);\n }\n });\n break;\n case FUNC_GEN:\n call = new Promise((resolve, reject) => {\n const gen = callable(...(Array.isArray(config.args) ? [...config.args] : []));\n try {\n resolve(gen.next().value);\n } catch (caughtGeneratorFunctionError) {\n reject(caughtGeneratorFunctionError);\n }\n });\n break;\n case OBJ_GEN:\n call = new Promise((resolve, reject) => {\n try {\n resolve(callable.next().value);\n } catch (caughtGeneratorError) {\n reject(caughtGeneratorError);\n }\n });\n delete config.args;\n break;\n default:\n call = new Promise((resolve, reject) => {\n Promise.resolve(callable).then(resolve).catch(reject);\n });\n delete config.args;\n }\n if (config.timeout !== undefined) {\n const timeout = Number.parseInt(`${config.timeout}`);\n if (Number.isFinite(timeout) && timeout > 0) {\n config.timeout = timeout > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : timeout;\n } else {\n delete config.timeout;\n }\n } else {\n delete config.timeout;\n }\n return (config.timeout\n ? Promise.race([\n Promise.resolve(call),\n new Promise((_resolve, reject) => {\n setTimeout(() => reject(new Error(`Timeout: ${config.timeout}ms`)), config.timeout);\n }),\n ])\n : Promise.resolve(call)\n )\n .then((result) => [result])\n .catch((caughtError) => {\n if (config.retries !== undefined) {\n const retries = Number.parseInt(config.retries);\n if (Number.isFinite(retries) && retries > 0) {\n config.retries = retries > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : retries;\n } else {\n delete config.retries;\n }\n } else {\n delete config.retries;\n }\n if (config.retries) {\n config.attempt = config.attempt === undefined ? 0 : config.attempt + 1;\n if (config.attempt < config.retries) {\n return ofAnyCase(callable, config);\n }\n }\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (config.error instanceof Error) {\n caughtError = config.error;\n } else if (typeof config.error === \"string\") {\n caughtError.message = config.error;\n }\n return [config.defaults, caughtError];\n });\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\n/**\n * @name ofCase\n * @param {Promise} promise\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function ofCase(promise, config = {}) {\n {\n const { args, defaults, error, timeout } = { ...config };\n config = { args, defaults, error, timeout };\n }\n if (config.timeout !== undefined) {\n const timeout = Number.parseInt(`${config.timeout}`);\n if (Number.isFinite(timeout) && timeout > 0) {\n config.timeout = timeout > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : timeout;\n } else {\n delete config.timeout;\n }\n } else {\n delete config.timeout;\n }\n return (config.timeout\n ? Promise.race([\n Promise.resolve(promise),\n new Promise((_resolve, reject) => {\n setTimeout(() => reject(new Error(`Timeout: ${config.timeout}ms`)), config.timeout);\n }),\n ])\n : Promise.resolve(promise)\n )\n .then((result) => [result, undefined])\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (config.error instanceof Error) {\n caughtError = config.error;\n } else if (typeof config.error === \"string\") {\n caughtError.message = config.error;\n }\n return [config.defaults, caughtError];\n });\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\n/**\n * @name ofError\n * @param {Promise} promise\n * @param {*=} overrideError\n * @returns {Promise<*>}\n */\nexport function ofError(promise, overrideError) {\n return Promise.resolve(promise)\n .then(() => undefined)\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (overrideError instanceof Error) {\n caughtError = overrideError;\n } else if (typeof overrideError === \"string\") {\n caughtError.message = overrideError;\n }\n return caughtError;\n });\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\n/**\n * @name ofIt\n * @param {Promise} promise\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function ofIt(promise, defaultResult, overrideError) {\n return Promise.resolve(promise)\n .then((result) => [result])\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n if (overrideError instanceof Error) {\n caughtError = overrideError;\n } else if (typeof overrideError === \"string\") {\n caughtError.message = overrideError;\n }\n return [defaultResult, caughtError];\n });\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\n/**\n * @name of\n * @param {Promise} promise\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\nexport function of(promise) {\n return Promise.resolve(promise)\n .then((result) => [result])\n .catch((caughtError) => {\n if (caughtError === undefined || caughtError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n }\n return [undefined, caughtError];\n });\n}\n","/**\n * @name ofResult\n * @param {Promise} promise\n * @param {*=} defaultResult\n * @returns {Promise<*>}\n */\nexport function ofResult(promise, defaultResult) {\n return Promise.resolve(promise)\n .then((result) => result)\n .catch(() => defaultResult);\n}\n","import { ERR_UNKNOWN } from \"../const/error.js\";\n\nimport { isFunction } from \"../util/isFunction.js\";\n\n/**\n * @name ofSync\n * @param {Function} callable\n * @param {[]=} args\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {[*, unknown] | [undefined, *]}\n */\nexport function ofSync(callable, args, defaultResult, overrideError) {\n if (!isFunction(callable)) {\n return [undefined, new Error(ERR_UNKNOWN)];\n }\n try {\n return [callable(...(Array.isArray(args) ? [...args] : [])), undefined];\n } catch (caughtFunctionError) {\n let caughtError;\n if (overrideError instanceof Error) {\n caughtError = overrideError;\n } else if (typeof overrideError === \"string\") {\n caughtFunctionError.message = overrideError;\n caughtError = caughtFunctionError;\n } else if (caughtFunctionError === undefined || caughtFunctionError === null) {\n caughtError = new Error(ERR_UNKNOWN);\n } else {\n caughtError = caughtFunctionError;\n }\n return [defaultResult, caughtError];\n }\n}\n","/**\n * @param {*} value\n * @returns {boolean}\n */\nexport function isFunction(value) {\n if (Object.prototype.toString.call(value) !== \"[object Function]\") {\n return false;\n }\n return !/^class\\s/.test(Function.prototype.toString.call(value));\n}\n","import { ofAnyCase } from \"./ofAnyCase.js\";\n\n/**\n * @name ofOutcome\n * @description Returns result or thrown error wherever happens\n * @param {Function|Promise} callable\n * @param {*=} config\n * @returns {Promise<*>}\n */\nexport function ofOutcome(callable, config = {}) {\n return new Promise((resolve) =>\n ofAnyCase(callable, config).then(([result, error]) => {\n resolve(error ? error : result);\n }),\n );\n}\n","import { ofAny } from \"../core/ofAny.js\";\nimport { ofAnyCase } from \"../core/ofAnyCase.js\";\nimport { ofCase } from \"../core/ofCase.js\";\nimport { ofError } from \"../core/ofError.js\";\nimport { ofIt } from \"../core/ofIt.js\";\nimport { of } from \"../core/of.js\";\nimport { ofResult } from \"../core/ofResult.js\";\nimport { ofSync } from \"../core/ofSync.js\";\nimport { ofOutcome } from \"../core/ofOutcome.js\";\n\nexport class Of {\n /**\n * @name any\n * @alias ofAny\n * @public\n * @static\n * @method\n * @param {Function|Promise} callable\n * @param {[]=} args\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static any = ofAny;\n /**\n * @name anyCase\n * @alias ofAnyCase\n * @public\n * @static\n * @method\n * @param {Function|Promise} callable\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static anyCase = ofAnyCase;\n /**\n * @name case\n * @alias ofCase\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static case = ofCase;\n /**\n * @name error\n * @alias ofError\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @param {*=} overrideError\n * @returns {Promise<*>}\n */\n static error = ofError;\n /**\n * @name it\n * @alias ofIt\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static it = ofIt;\n /**\n * @name async\n * @alias of\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static async = of;\n /**\n * @name result\n * @alias ofResult\n * @public\n * @static\n * @method\n * @param {Promise} promise\n * @param {*=} defaultResult\n * @returns {Promise<*>}\n */\n static result = ofResult;\n /**\n * @name sync\n * @alias ofSync\n * @public\n * @static\n * @method\n * @param {Function} callable\n * @param {[]=} args\n * @param {*=} defaultResult\n * @param {*=} overrideError\n * @returns {[*, unknown] | [undefined, *]}\n */\n static sync = ofSync;\n /**\n * @name outcome\n * @alias ofOutcome\n * @public\n * @static\n * @method\n * @param {Function|Promise} callable\n * @param {*=} config\n * @returns {Promise<[*, unknown] | [undefined, *]>}\n */\n static outcome = ofOutcome;\n}\n"],"names":["ERR_UNKNOWN","ofAny","callable","args","defaultResult","overrideError","call","constructor","name","Object","prototype","toString","Array","isArray","Promise","resolve","reject","caughtFunctionError","gen","next","value","caughtGeneratorFunctionError","caughtGeneratorError","then","catch","result","caughtError","Error","message","ofAnyCase","config","defaults","error","retries","timeout","undefined","Number","parseInt","isFinite","MAX_SAFE_INTEGER","race","_resolve","setTimeout","attempt","ofCase","promise","ofError","ofIt","of","ofResult","ofSync","isFunction","test","Function","ofOutcome","Of"],"mappings":"sIAAO,MAAMA,EAAc,gBCWpB,SAASC,MAAMC,EAAUC,EAAMC,EAAeC,OAC/CC,SACIJ,EAASK,YAAYC,MAAQC,OAAOC,UAAUC,SAASL,KAAKJ,QCT/C,UDWjBI,EAAOJ,YCda,gBDiBpBI,EAAOJ,KAAaU,MAAMC,QAAQV,GAAQ,IAAIA,GAAQ,cClBxC,WDqBdG,EAAO,IAAIQ,QAAQ,CAACC,EAASC,SAEzBD,EAAQb,KAAaU,MAAMC,QAAQV,GAAQ,IAAIA,GAAQ,KACvD,MAAOc,GACPD,EAAOC,gBCvBO,oBD4BlBX,EAAO,IAAIQ,QAAQ,CAACC,EAASC,WACrBE,EAAMhB,KAAaU,MAAMC,QAAQV,GAAQ,IAAIA,GAAQ,QAEzDY,EAAQG,EAAIC,OAAOC,OACnB,MAAOC,GACPL,EAAOK,gBChCM,qBDqCjBf,EAAO,IAAIQ,QAAQ,CAACC,EAASC,SAEzBD,EAAQb,EAASiB,O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AASzC,UACzBU,QAAQC,QAAQ8B,GACpBtB,KAAME,GAAWA,GACjBD,MAAM,IAAMpB,GCGV,SAAS8C,OAAOhD,EAAUC,EAAMC,EAAeC,OCR/C,SAAS8C,WAAW/B,SACqB,sBAA1CX,OAAOC,UAAUC,SAASL,KAAKc,KAG3B,WAAWgC,KAAKC,SAAS3C,UAAUC,SAASL,KAAKc,IDKpD+B,CAAWjD,SACP,MAACiC,EAAW,IAAIR,MAAM3B,cAGtB,CAACE,KAAaU,MAAMC,QAAQV,GAAQ,IAAIA,GAAQ,SAAMgC,GAC7D,MAAOlB,OACHS,SACArB,aAAyBsB,MAC3BD,EAAcrB,EACoB,iBAAlBA,GAChBY,EAAoBW,QAAUvB,EAC9BqB,EAAcT,GAEdS,EADST,MAAAA,EACK,IAAIU,MAAM3B,GAEViB,EAET,CAACb,EAAesB,IErBpB,SAAS4B,UAAUpD,EAAU4B,EAAS,WACpC,IAAIhB,QAASC,GAClBc,UAAU3B,EAAU4B,GAAQP,KAAK,EAAEE,EAAQO,MACzCjB,EAAQiB,GAAgBP,MCFvB,MAAM8B,oBAAAA,SAaEtD,uBAbFsD,aAwBM1B,2BAxBN0B,UAmCGX,wBAnCHW,WA8CIT,yBA9CJS,QA0DCR,sBA1DDQ,WAoEIP,oBApEJO,YA+EKN,0BA/ELM,UA4FGL,wBA5FHK,aAuGMD"} --------------------------------------------------------------------------------