Promises and Async/Await patterns have greatly improved multi-tasking in JavaScript. With the inroduction of Web Workers and Node.JS Worker Threads marked as stable, true multi-threading has become a cross-platform reality as well. This library aims to combine Promise
and Worker
dynamically to provide single-task, easy-to-use asynchrony, and pooling (using PromiseWorker.all
) for threads.
The library is usable in browsers and Node.JS. There are some differences which are explained below.
- Node.JS:
const { PromiseWorker } = require('promise-workers')
- TypeScript:
import { PromiseWorker } from 'promise-workers'
- Tree-shaking with ESM:
import { PromiseWorker } from 'promise-workers/esm/index.js'
- Browser:
<script type="module" src="https://cdn.jsdelivr.net/npm/[email protected]/esm/index.min.js"></script>
For use with TypeScript, it's recommended to install the optional dependency of tslib
.
function workToDo (input) {
return new PromiseWorker(function () {
const data = workerData // Variable workerData is assigned as a constant in the worker context.
// Perform CPU/time intensive work...
return data
}, { workerData: input })
}
async function main () {
try {
const result = await workToDo(300)
console.log(result)
} catch (error) {
console.log(error)
}
}
main()
// ... Do other work
The PromiseWorker
constructor accepts two arguments.
executor
: Required The function passed to the worker for execution.workerData
: Optional Any JavaScript value which will be cloned to the worker as a localworkerData
variable.
The executor
function should be written as if it is self-contained code. It will be executed in the context of the worker and will only have access to the context of its own thread. The variable workerData
is initialized as a constant in the worker context and cannot be re-assigned by the executor
function. The executor
function cannot reference anything from the parent thread that spawns the PromiseWorker
.
workerData: T
- The payload to pass into the worker context.[option: string]: any
- Any additional options to pass to the underlying worker.
new PromiseWorker(executor: (resolve: (value?: unknown) => void, reject: (reason?: any) => void) => void)
Creates a worker with a Promise to fulfill.
new PromiseWorker(executor: (resolve: (value?: unknown) => void, reject: (reason?: any) => void) => void, options: PromiseWorkerOptions)
Creates a worker with a Promise to fulfill; passes data to the local context as const workerData
.
Calls Promise.all
for convenience and Promise API completeness.
Calls Promise.allSettled
for convenience and Promise API completeness.
Method set on PromiseWorker
to throw an error alerting users to avoid. See StackExchange thread on multi-threading pitfalls for great discussion and insight on why racing threads is bad. Although the other executing PromiseWorkers should terminate gracefully, insight into those other threads is lost and it becomes difficult to determine if those threads have been handled in a stable manner. If you really do wish to circumvent this, just call Promise.race
directly.
Calls Promise.reject
for convenience and Promise API completeness.
Calls Promise.resolve
for convenience and Promise API completeness.
Web browsers and Node are supported by this library. This is limited to the availability and implementation of class Worker
on each platform.This library has been tested working in Chrome 80.0.3987.132, Firefox 68.6.0esr, and Edge 44.18362.449.0.
Platform | Versions | Async Function Resolve Value | Sync Function Resolve Value | Reject Error |
---|---|---|---|---|
Node | 12.x , 13.x |
The value passed to resolve() |
The function return value | Value passed to reject() or a JS Error |
Browser | See MDN docs | The value* passed to resolve() ** |
The function return value* | An ErrorEvent object |
* The value is explicitly taken from the MessageEvent.data
property, instead of returning the whole MessageEvent
.
** It is expected that the user will write their code so that the executor passes a value to resolve
and/or reject
.
Feature | Node | Browser |
---|---|---|
Functions and Classes | Node Docs | MDN Docs |
Worker constructor | Executable code is passed as a string | Code is stringified and turned into a Blob URL |
PromiseWorker runtime | workerData is passed directly in constructor |
worker.postMessage() is used to pass workerData to the thread |
- Aaron Huggins