{"id":22314438,"url":"https://github.com/alvarobernalg/event-worker","last_synced_at":"2025-09-13T07:15:07.401Z","repository":{"id":22948825,"uuid":"97760165","full_name":"AlvaroBernalG/event-worker","owner":"AlvaroBernalG","description":"A simpler way of dealing with Web Workers","archived":false,"fork":false,"pushed_at":"2023-01-13T22:17:34.000Z","size":1845,"stargazers_count":19,"open_issues_count":29,"forks_count":3,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-11-24T19:20:20.954Z","etag":null,"topics":["events","listener","performance","process","promise","thread","threads","web","worker"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AlvaroBernalG.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-07-19T20:51:22.000Z","updated_at":"2022-08-31T04:40:03.000Z","dependencies_parsed_at":"2023-01-13T22:30:19.131Z","dependency_job_id":null,"html_url":"https://github.com/AlvaroBernalG/event-worker","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/AlvaroBernalG%2Fevent-worker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlvaroBernalG%2Fevent-worker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlvaroBernalG%2Fevent-worker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlvaroBernalG%2Fevent-worker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AlvaroBernalG","download_url":"https://codeload.github.com/AlvaroBernalG/event-worker/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228006260,"owners_count":17854996,"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":["events","listener","performance","process","promise","thread","threads","web","worker"],"created_at":"2024-12-03T22:10:01.412Z","updated_at":"2024-12-03T22:10:02.588Z","avatar_url":"https://github.com/AlvaroBernalG.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# event-worker\n\u003e Minimalistic event/promified driven web worker abstraction.\n\n[![Build Status](https://travis-ci.org/AlvaroBernalG/event-worker.svg?branch=master)](https://travis-ci.org/AlvaroBernalG/event-worker) [![npm version](https://badge.fury.io/js/event-worker.svg)](https://badge.fury.io/js/event-worker) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)\n\n## Install\n\n### npm\n```shell\nnpm install event-worker --save\n```\n\n### CDN\n\nhttps://cdn.jsdelivr.net/npm/event-worker@1.3.0/index.min.js\n\n\n## Usage\n\nBasic example\n\nIn your main thread (main.js):\n\n```js\nconst EventWorker = require('event-worker')\n\nconst worker = new EventWorker('path/to/my/worker.js')\n\nasync function test(){\n  const user = await worker.emit('getUserById', { id: '30242' })\n\n  /*\n  {\n    id: '30242',\n    name: 'neil',\n    lastname: 'tyson degrasse'\n  }\n  */\n//...\n\n```\n\nAnd then in your web worker (worker.js) you can listen for that event and respond back with the requested data:\n\n```js\nconst EventWorker = require('event-worker')\n\nconst worker = new EventWorker()\n\nworker.on('getUserById', async ({payload}) =\u003e {\n\n  let user = await getUser(payload.id)\n\n  return user // Respond back to the main thread with the data requested.\n\n})\n\n\nasync function getUser(id){\n\n  let user = await fetchUserFromLocalDatabase(id)\n\n  if(user) return user\n\n  user = await fetchUserFromServer(id)\n\n  saveUserInLocaDatabase(user)\n\n  return user\n}\n```\n\n### Workload splitting\n\nIf you want to keep your main thread running smoothly dividing the work load of expensive computational task between multiple web workers becomes easier.\n\nFrom main thread (main.js):\n\n```js\nconst EventWorker = require('event-worker')\n\nconst workerPath = 'path/to/my/worker.js'\n\nconst workerPool = [\n  new EventWorker(workerPath),\n  new EventWorker(workerPath),\n  new EventWorker(workerPath)\n]\n\nconst sum = (a, b) =\u003e a + b\n\nconst multiplyBy2InOtherThread = (worker, index) =\u003e worker.emit('multiply_by_2', index)\n\n(async ()=\u003e\n  (await Promise.all(\n    workerPool.map(multiplyBy2InOtherThread)\n  )).reduce(sum, 0)\n)() // 6\n\n```\n\nFrom worker (worker.js):\n\n```js\n\nimportScripts('path/to/source/event-worker.js')\n\nconst worker = new EventWorker()\n\nworker.on('multiply_by_2', ({payload}) =\u003e payload * 2 )\n\n```\n\n#### Bidirectional communication\n\nYou can listen for events triggered by your workers.\n\nFrom main thread (main.js):\n\n```js\n//...\n\nworker.on('interestingData', ({payload})=\u003e{\n\n  doSomethingWithInterestingData(payload)\n\n  return 'Good job worker!'\n\n})\n\n//..\n```\n\nFrom worker (worker.js):\n\n```js\n\n//...\nconst res = await worker.emit('interestingData', 'interestingString')\n\nres // =\u003e 'Good job worker!!'\n\n```\n\n#### Inlining code\n\nInstead of having a separate file for your worker, you can wrap your code inside a function and pass it as\nan argument to the constructor of EventWorker. This is a good option when prototyping.\n\nFrom main (main.js):\n\n```js\n\nconst worker = new EventWorker(async (mainThread) =\u003e {\n\n  let res = await mainThread.emit('sayingHiFromWorker', 'Hi main thread!')\n\n  console.log(res) // Hello worker!\n\n})\n\nworker.on('sayingHiFromWorker', ({payload}) =\u003e {\n\n  console.log(payload) // Hi main thread!\n\n  return \"Hello worker!\"\n\n})\n```\n\n#### Caveat\n\nWhen you inline functions it is easy to get confused by the execution context. If you try to access a variable that is outside the scope of the inline function it will fail.\n\n```js\n\nconst favoriteAnimal = 'chiguire'\n\nconst worker = new EventWorker(async (mainThread) =\u003e {\n  // This will get executed in a worker.\n  mainThread.on('onGetAnimals', ()=\u003e{\n\n    console.log(favoriteAnimal) // fails. favoriteAnimal variable is not in the same execution context.\n\n    //...\n  })\n\n})\n\n```\n\n#### Error Handling\n\nError handling works the same as you would expect from a promise executed in the same thread:\n\nFrom main thread (main.js):\n\n```js\nconst EventWorker = require('event-worker')\n\nconst worker = new EventWorker('path/to/my/worker.js')\n\nworker.emit('rejectThisCall')\n  .catch((reason) =\u003e {\n    console.log(`Rejected because: \"${reason}\" `)\n  })\n\n```\n\nFrom worker (worker.js):\n\n```js\n\nimportScripts('path/to/source/event-worker.js')\n\nconst worker = new EventWorker()\n\n//throwing errors\nworker.on('rejectThisCall', () =\u003e {\n  throw new Error()\n})\n\n// throwing async errors\nworker.on('rejectThisCallAsync', async ()=\u003e {\n  throw new Error()\n})\n\n```\n\nInstead of embedding event-worker into your worker file with a module bundler, you can use the built in function `importScripts`:\n\n```js\n\nimportScripts('path/to/source/event-worker.js')\n\nconst worker = new EventWorker()\n\n// ...\n```\n\nEventWorker reference is injected into the global scope once it's loaded.\n\n\n## API\n\n### new EventWorker(source) `EventWorker`\n\nCreates a new instance\n\n  * source `string | function | undefined`\n\n    * If a string is passed: It will assume it is the worker source file path.\n\n    * If a function is passed it will get converted into a string an then transformed into a worker.\n\n    * If nothing (undefined) is passed it will assume that the environment is the worker.\n\n### emit(eventName, data) `Promise`\n\nEmits a event.\n\n  * eventName `String`\n\n  * data `Any`\n\n### on(eventName, callback) `EventWorker`\n\nRegisters for an event.\n\n* eventName\n\n* callback `function(object) =\u003e Promise\u003cany\u003e`\n\n  Gets executed when eventName is emited.\n\n  * object\n    * object.payload `any`\n\n      Data sent from the event emitter to the listener.\n\n### terminate() `void`\n\nImmediately terminates the Worker. This does not offer the worker an opportunity to finish its operations; it is simply stopped at once.\n\n## Changelog\n\n### 2017-11-04 \n  * Removed `\"resolve\"` and `\"reject\"` function properties in the `\"on\"` callback. \n\n## Contributing\n\nAll contributions are welcome.\n\n## License\n\nMIT © [Alvaro Bernal](https://github.com/AlvaroBernalG/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falvarobernalg%2Fevent-worker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falvarobernalg%2Fevent-worker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falvarobernalg%2Fevent-worker/lists"}