{"id":21571126,"url":"https://github.com/cheprasov/js-worker-thread","last_synced_at":"2025-03-18T06:15:23.889Z","repository":{"id":33869284,"uuid":"162766617","full_name":"cheprasov/js-worker-thread","owner":"cheprasov","description":"The WorkerThread wraps a Web Worker with a Promise, also the class creates a worker script on the fly (without having to create separate worker files). You can \"inline\" your worker function in the same js file as main logic. ","archived":false,"fork":false,"pushed_at":"2023-01-03T15:45:36.000Z","size":879,"stargazers_count":1,"open_issues_count":16,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-26T11:20:39.858Z","etag":null,"topics":["promise","thread","webworker"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cheprasov.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":"cheprasov","patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":null}},"created_at":"2018-12-21T23:32:12.000Z","updated_at":"2021-06-10T19:43:51.000Z","dependencies_parsed_at":"2023-01-15T03:04:12.156Z","dependency_job_id":null,"html_url":"https://github.com/cheprasov/js-worker-thread","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cheprasov%2Fjs-worker-thread","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cheprasov%2Fjs-worker-thread/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cheprasov%2Fjs-worker-thread/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cheprasov%2Fjs-worker-thread/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cheprasov","download_url":"https://codeload.github.com/cheprasov/js-worker-thread/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244110170,"owners_count":20399562,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["promise","thread","webworker"],"created_at":"2024-11-24T11:14:58.025Z","updated_at":"2025-03-18T06:15:23.871Z","avatar_url":"https://github.com/cheprasov.png","language":"JavaScript","funding_links":["https://github.com/sponsors/cheprasov"],"categories":[],"sub_categories":[],"readme":"[![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT)\n\n@cheprasov/worker-thread\n=========\n\nThe WorkerThread wraps a Web Worker with a Promise, also the class creates a worker script on the fly (without having to create separate worker files). You can \"inline\" your worker function in the same js file as main logic.\n\n##### Features:\n- Wraps a Web Worker with a Promise.\n- You do not need to use separate js file for a Web Worker.\n- You can use function or string with code to create a Web Worker.\n- Will simulate a worker via timeout if Web Worker is not supported.\n- Allows to throw an Error in Worker scope, and catch it by Promise.\n\n### 1. How to install\n\n```bash\n\u003e npm install @cheprasov/worker-thread\n```\n\n```javascript\nimport { ThreadFactory } from '@cheprasov/worker-thread';\n```\n\n### 2. Quick examples\n\nSimple function for sum\n\n```javascript\nimport { ThreadFactory } from '@cheprasov/worker-thread';\n\nconst threadSumAB = ThreadFactory.createThread((a, b) =\u003e a + b);\n\nthreadSumAB.exec(2, 3).then((result) =\u003e {\n    console.log('a + b =', result);\n    // a + b = 5\n});\n\nconst threadSumMulti = ThreadFactory.createThread((...args) =\u003e {\n    return args.reduce((result, value) =\u003e result + value, 0);\n});\n\nthreadSumMulti.exec(1, 2, 3, 4, 5).then((result) =\u003e {\n    console.log('a1 + ... + aN =', result);\n    // a1 + ... + aN = 15\n});\n```\n\nThread functions can return objects, arrays and so on\n\n```javascript\nconst threadDeepCopyObject = ThreadFactory.createThread(obj =\u003e obj);\n\nconst obj1 = { foo: 'bar', num: 42 };\nthreadDeepCopyObject.exec(obj1).then((copyObj) =\u003e {\n    copyObj.foo = 'upd';\n    console.log('Copy', copyObj, 'Orig', obj1);\n    // Copy {foo: \"upd\", num: 42} Orig {foo: \"bar\", num: 42}\n});\n```\n\nSeveral function in one thread\n\n```javascript\nconst threadMultiCmd = ThreadFactory.createThread((cmd, a, b) =\u003e {\n    switch (cmd) {\n        case 'sum': return a + b;\n        case 'max': return Math.max(a, b);\n        default: return null;\n    }\n});\n\nthreadMultiCmd.exec('sum', 1, 2).then((result) =\u003e {\n    console.log('Cmd: sum, a + b =', result);\n    // Cmd: sum, a + b = 3\n});\n```\n\nErrors. Thread allows to throw an Errors and catch it by Promise\n\n```javascript\nconst throwError = ThreadFactory.createThread((num) =\u003e {\n    if (!num) {\n        throw new Error('Some message');\n    }\n    if (num === 42) {\n        // the code works in DedicatedWorkerGlobalScope\n        // see https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope\n        return self;\n    }\n    return 1 / num;\n});\n\nconst onError = (error) =\u003e {\n    console.log(`${error.type}: ${error.message}`);\n};\n\nthrowError.exec(0).then().catch(onError);\n// Error: Some message\n\nthrowError.exec(42).then().catch(onError);\n// DataCloneError: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': #\u003cDedicatedWorkerGlobalScope\u003e could not be cloned.\n```\n\n### 3. Documentation\n\n#### Class `ThreadFactory`\nIt is a factory class for creating instances of WorkerThread, TimeoutThread, NoopTread.\n\n##### `static` createThread(function, options): `WorkerInterface`\nThe method will creates an instance of `WorkerThread` if Web Worker is supported, otherwise it will create an instance of `TimeoutThread` if function `setTimeout` is supported, otherwise it will create an instance of `NoopThread`.\n\nThe method helps to run your code for wide range of browser by running workers code via timeout (`TimeoutThread`) if the browser does not support Web Workers.\n\n**arguments:**\n\n- `function` - the function that will be used for web worker. \n- `options` - `default = {}` Parameters for a new worker. See more here: https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker\n    - `importScripts` - `default = []` - Array of strings. A list of scripts which Web Worker for work. https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts\n    - `name` - see https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker#Parameters\n    - `type` - see https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker#Parameters\n    - `credentials` - see https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker#Parameters\n    - `onError`: Function - A function that will be called if an error is occurred on creating of Web Worker. The function receives `ErrorEvent` as argument.\n    \nExample: \n```javascript\nimport { ThreadFactory } from '@cheprasov/worker-thread';\n\nconst threadSum = ThreadFactory.createThread(\n        (a, b) =\u003e a + b,\n        {\n            importScripts: ['foo.js', 'bar.js'],\n            onError: (error) =\u003e {\n                // it will be error, because it can import specified scripts \n                console.log('Error', error);\n            },\n        }\n    );\n\n```\n\n##### `static` createWorkerThread(function | string, options): `WorkerThread`\nThe method creates an instance of `WorkerThread` without any checking for support.\nSee method `createThread` for description of arguments.  \n\n##### `static` createTimeoutThread(function, options): `TimeoutThread`\nThe method creates an instance of `TimeoutThread` without any checking for support.\nSee method `createThread` for description of arguments.  \n\n##### `static` createNoopThread(function, options): `NoopThread`\nThe method creates an instance of `NoopThread` without any checking for support.\nSee method `createThread` for description of arguments.  \n\n\n#### Class `WorkerThread`\nThe WorkerThread wraps a Web Worker with a Promise, also the class creates a worker script on the fly (without having to create separate worker files). You can \"inline\" your worker function in the same js file as main logic.\n\nSee more https://developer.mozilla.org/en-US/docs/Web/API/Worker\n\n##### `static` isSupported(): `boolean`\nMethod checks browser for support of `WorkerThread`\n\n##### constructor(Function | string, options)\nAlso, please see `ThreadFactory`.\n\n**arguments:**\n\n- `function` - the function that will be used for web worker. Also, you can user string with code for worker.\n- `options` - `default = {}` Parameters for a new worker. See more here: https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker\n    - `importScripts` - `default = []` - Array of strings. A list of scripts which Web Worker for work. https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts\n    - `name` - see https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker#Parameters\n    - `type` - see https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker#Parameters\n    - `credentials` - see https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker#Parameters\n    - `onError`: Function - A function that will be called if an error is occurred on creating of Web Worker. The function receives `ErrorEvent` as argument.\n    \n##### exec(...args): `Promise`\nThe methods executes worker's function and passes arguments to it, and returns of `Promise`, which will be resolved when the function is finished.\n\n##### close(): `Promise`\nThe method of the DedicatedWorkerGlobalScope interface discards any tasks queued in the DedicatedWorkerGlobalScope's event loop, effectively closing this particular scope. \n\n##### terminate(): `void`\nThe method immediately terminates the Worker. This does not offer the worker an opportunity to finish its operations; it is simply stopped at once.\n\nExample:\n```javascript\nimport { WorkerThread } from '@cheprasov/worker-thread';\n\nconst threadSum = new WorkerThread((a, b) =\u003e a + b);\n\nthreadSum.exec(2, 3).then((result) =\u003e {\n    console.log('a + b =', result);\n    // a + b = 5\n    threadSum.close();\n});\n```\n\n\n#### Class `TimeoutThread`\nThe `TimeoutThread` emulates `WorkerThread` via using `setTimeout` function.\n\nSee more https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout\n\n##### `static` isSupported(): `boolean`\nMethod checks browser for support of `TimeoutThread`\n\n##### constructor(Function)\nAlso, please see `ThreadFactory`.\n\n**arguments:**\n\n- `function` - the function that will be used.\n    \n##### exec(...args): `Promise`\nThe methods executes work function and passes arguments to it, and returns of `Promise`, which will be resolved when the function is finished.\n\n##### close(): `Promise`\nThe method immediately stops the work function. This does not offer an opportunity to finish its operations.\n\n##### terminate(): `void`\nThe same like method `close()`, but without a `Promise`\n\nExample:\n```javascript\nimport { TimeoutThread } from '@cheprasov/worker-thread';\n\nconst threadSum = new TimeoutThread((a, b) =\u003e a + b);\n\nthreadSum.exec(2, 3).then((result) =\u003e {\n    console.log('a + b =', result);\n    // a + b = 5\n});\n```\n\n\n#### Class `NoopThread`\nThe `NoopThread` is a stub and it does nothing. \n\n##### `static` isSupported(): `boolean`\nAlways return `true`;\n\n##### exec(...args): `Promise`\n##### close(): `Promise`\n##### terminate(): `void`\n\nThe methods do nothing.\n\n\n#### Error class `WorkerError`\nAll thrown error in Web Worker's code will be returned to a `Promise` like instance of `WorkerError`.\n\nThe error has `type`, `message` and `data`.\n\n```javascript\nconst threadError = ThreadFactory.createThread((num) =\u003e {\n    if (!num) {\n        throw new Error('Some message');\n    }\n    if (num === 42) {\n        // the code works in DedicatedWorkerGlobalScope\n        // see https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope\n        return self;\n    }\n    return 1 / num;\n});\n\nconst onError = (error) =\u003e {\n    console.log(`${error.type}: ${error.message}`);\n};\n\nthreadError.exec(0).then().catch(onError);\n// Error: Some message\n\nthreadError.exec(42).then().catch(onError);\n// DataCloneError: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': #\u003cDedicatedWorkerGlobalScope\u003e could not be cloned.\n```\n\n## Something does not work\n\nFeel free to fork project, fix bugs, tests and finally request for pull\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcheprasov%2Fjs-worker-thread","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcheprasov%2Fjs-worker-thread","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcheprasov%2Fjs-worker-thread/lists"}