Skip to content

Execute Web Workers as promise without dedicated script file

License

Notifications You must be signed in to change notification settings

xan105/web-worker-thread

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

About

Execute Web Workers as promise without dedicated script file.

📦 Scoped @xan105 packages are for my own personal use but feel free to use them.

Example

import { threadify } from "@xan105/web-worker-thread";

function fibonacci(n) {
  if (n <= 1n) return n;
  let a = 0n, b = 1n;
  for (let i = 2n; i <= n; i = i + 1n) {
    [a, b] = [b, a + b];
  }
  return b;
}

const n = await threadify(fibonacci)(100000n);
console.log(n);

This can be used as a "coroutine-like" with an AbortController:

import { threadify } from "@xan105/web-worker-thread";

function timer(i){
  return new Promise((resolve) => setTimeout(() => resolve(), i));
}

const controller = new AbortController();
const { signal } = controller;
threadify(timer, { signal })(500).catch(console.error);
setTimeout(() => controller.abort(), 100);

Install

npm i @xan105/web-worker-thread

💡 The bundled library and its minified version can be found in the ./dist folder.

Via importmap

Create an importmap and add it to your html:

  <script type="importmap">
  {
    "imports": {
      "@xan105/web-worker-thread": "./path/to/node_modules/@xan105/web-worker-thread/dist/thread.min.js"
    }
  }
  </script>
  <script src="./index.js" type="module"></script>
  </body>
</html>

index.js:

  import { threadify } from "@xan105/web-worker-thread"
  await threadify(foo)("bar");

API

⚠️ This module is only available as an ECMAScript module (ESM) and is intended for the browser.

Named export

threadify(fn: function | Promise, option?: object): (...args: unknown[]) => Promise<unknown>

Spawn a web worker and run the given function (sync or async) inside the web worker.

ℹ️ Usage is similar to node:util/promisify syntax:

import { threadify } from "@xan105/web-worker-thread";

function double(i){
  return i * 2;
}

const i = await threadify(double)(2);
console.log(i); //4

⚙️ Options

{
  timeout?: number,
  importScripts?: string[],
  signal?: AbortSignal
}
  • timeout?: number (0)

Optional timeout (in ms) to cancel the web worker if it takes too much time.

  • importScripts?: string[] (none)

Optional array of script path(s) to import into the web worker's scope.
See importScripts for more details.

  • signal?: AbortSignal (none)

Optional Abort controller signal to abort the web worker.
See AbortController for more details.

↩️ Return

Returns a function that, when called with any arguments, executes the original function in a separate thread (web worker) and returns a Promise that:

  • ✔️ resolves to the original function's result
  • ❌ or rejects on error

About

Execute Web Workers as promise without dedicated script file

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

  •