https://github.com/shilangyu/async-worker
Parallel code execution wrapped in promises ⭐
https://github.com/shilangyu/async-worker
async-functions async-js async-worker thread-workers web-workers
Last synced: 10 months ago
JSON representation
Parallel code execution wrapped in promises ⭐
- Host: GitHub
- URL: https://github.com/shilangyu/async-worker
- Owner: shilangyu
- License: mit
- Created: 2019-04-17T18:46:44.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2025-06-02T06:25:12.000Z (11 months ago)
- Last Synced: 2025-06-26T01:46:39.838Z (11 months ago)
- Topics: async-functions, async-js, async-worker, thread-workers, web-workers
- Language: TypeScript
- Homepage: https://github.shilangyu.dev/async-worker/
- Size: 729 KB
- Stars: 12
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://github.com/shilangyu/async-worker/actions)
[](https://david-dm.org/shilangyu/async-worker)
[](https://snyk.io/test/github/shilangyu/async-worker?targetFile=package.json)
[](https://github.com/shilangyu/async-worker/issues)
[](https://opensource.org/licenses/mit-license.php)
✨ Enhance your asynchronous web/node development by sprinkling parallel code execution! ✨
- [installing](#installing)
- [API](#api)
- [task](#task)
- [cook](#cook)
- [track](#track)
- [kill](#kill)
- [common mistakes](#common-mistakes)
[DEMO](https://github.shilangyu.dev/async-worker/)
### installing
Install from npm:
```sh
npm i async-worker
```
Import:
```ts
import AsyncWorker from 'async-worker'
```
Alternatively use the embedded script tag (`AsyncWorker` will be available globally):
```html
```
### API
#### task
To perform a long, expensive tasks outside of the main thread use `asyncWorker.task`
```ts
const { task } = new AsyncWorker()
const primes = await task(
(from, to) => {
let computedPrimes = []
// im computing big data that would otherwise block the main thread
return computedPrimes
},
10,
1000000
)
```
```ts
function task(func: (...args: S) => T, ...args: S): Promise
```
#### cook
To cook a function into an asynchronous one use `asyncWorker.cook`
```ts
const { cook } = new AsyncWorker()
const asyncFibo = cook(() => (n) => {
if (n <= 0) return NaN
let [first, second] = [0, 1]
while (--n) [first, second] = [second, first + second]
return first
})
const res = await asyncFibo(5)
console.log(`5th fibonacci number is ${res}`)
```
```ts
function cook(
func: (...args: S) => (...args: U) => T,
...args: S
): (...args: U) => Promise
```
#### track
To track progress of a task use `asyncWorker.track`
```ts
const { track } = new AsyncWorker()
const tracker = track((tick, n) => {
let fact = 1
for (let i = 1; i <= n; i++) {
fact *= i
tick(i / n)
}
return fact
}, 15)
tracker.tick((progress) => console.log(`the factorial is ${progress * 100}% done!`))
console.log(`the result is ${await tracker.result}`)
```
```ts
function track(
func: (tick: (progress: number) => void, ...args: S) => T,
...args: S
): {
result: Promise
tick: (ticker: (progress: number) => void) => void
}
```
#### kill
Once you're done using, you can kill it
```ts
const async = new AsyncWorker()
async.task(/* doing something */)
async.kill()
```
### common mistakes
Because web workers/worker threads exist in a different thread the passed function does not have access to your current context variables. To pass in variables please add them as additional parameters and accept them in your functions. This will **not** work:
```ts
//...
const from = 10
const to = 1000000
const primes = await task(() => {
console.log(from) // error during worker runtime: 'from' is not defined
console.log(to) // error during worker runtime: 'to' is not defined
})
//...
```
Do instead:
```ts
//...
const from = 10
const to = 1000000
const primes = await task(
(from, to) => {
console.log(from) // :)
console.log(to) // :)
},
from,
to
)
//...
```
Some types are not [transferable](https://developer.mozilla.org/en-US/docs/Web/API/Transferable). Meaning you cannot send them to or receive from a web worker. Notably functions are not transferable. The following will **not** work:
```ts
//...
const answer = () => 42
const result = await task((answer) => {
// DataCloneError: could not clone '() => 42'
}, answer)
//...
```
Nor will:
```ts
//...
const func = await task(() => {
return () => 42
// DataCloneError: could not clone '() => 42'
})
//...
```