An open API service indexing awesome lists of open source software.

https://github.com/xan105/web-worker-thread

Execute Web Workers as promise without dedicated script file
https://github.com/xan105/web-worker-thread

blob browser coroutine thread web-workers

Last synced: 4 months ago
JSON representation

Execute Web Workers as promise without dedicated script file

Awesome Lists containing this project

README

          

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
=======

```js
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:

```js
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:

```html

{
"imports": {
"@xan105/web-worker-thread": "./path/to/node_modules/@xan105/web-worker-thread/dist/thread.min.js"
}
}