async-thread-worker

async-thread-worker

An async/await abstraction for Web Workers

npm MIT licensed CI

About

async-thread-worker presents an abstraction of Web Worker thread communication based on the client-server model. Supported features are:

After introducing some basic examples for quickly getting started, we demonstrate applications using Wasm binaries (C code compiled by Emscripten and Rust code by wasm-pack) embedded inside worker threads.

For other libraries that realize similar functionality, you might also consider:

Getting Started

Installation

$ npm install async-thread-worker

Usage

Here’s a basic example of implementing a worker (abstracted as thread) and interacting with it. Use sendRequest() and sendResponse() for client-server style communications. [ demo | source ]

index.html: Synchronously sending requests to a worker.

// <script src='async-thread-worker.min.js'></script>

const thread = new AsyncThreadWorker.Thread('my-thread-worker.js');

for (let payload of ['a', 'b', 'c', 'd']) {
    const response = await thread.sendRequest(payload);
    console.log('[main] got response:', response);
}

my-thread-worker.js: Implementation of the worker. Use the provided id to respond to a request.

importScripts('async-thread-worker.min.js');

class MyThreadWorker extends AsyncThreadWorker.ThreadWorker {
    onRequest(id, payload) { // impl
        console.log('[worker] got request with:', payload);
        this.sendResponse(id, payload.toUpperCase());
    }
}
const myThreadWorker = new MyThreadWorker(self);

The results in the developer console:

[worker] got request: a
[main] got response: A
[worker] got request: b
[main] got response: B
[worker] got request: c
[main] got response: C
[worker] got request: d
[main] got response: D

Examples

API

AsyncThreadWorker.Thread

The Thread class is for abstraction of the main thread’s side (client).

AsyncThreadWorker.ThreadWorker

The ThreadWorker class is for abstraction of the worker’s side (server).

Build

$ npm install  # set up build tools
$ npm run build