Skip to content

A Promise API for submitting requests to workers and tracking responses.

License

Notifications You must be signed in to change notification settings

illright/worker-request-response

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

worker-request-response 👷‍♀️💬🗨️

npm version minzipped package size

Ever wish you could request some data from a service/web worker and have them respond to you asynchronously?

A Promise API for submitting requests to workers and tracking responses.

Installation

pnpm add worker-request-response

Type definitions are built in 😎.

I don't use pnpm

What do you mean "I don't use pnpm"? It's so much faster! Alright, here's your npm command:

npm install --save worker-request-response

Usage

It has two functions exported:

  • sendRequest for your main thread code
  • handleRequestsWith for your worker code

Here's an example of a service worker that converts numbers to strings:

// In your main thread
import { sendRequest } from 'worker-request-response';

export async function sendRequestToServiceWorker() {
  const response = await sendRequest<number, string>(navigator.serviceWorker.controller, 42);
  console.log(response, 'is "42"');
}
// In your worker
import { handleRequestsWith } from 'worker-request-response';

async function processRequest(event: MessageEvent<number>): Promise<string> {
  return event.data.toString();
}

self.addEventListener('message', handleRequestsWith(processRequest));

There, that simple. In glorious TypeScript, too.

Usage with web workers

The sendRequest function accepts the worker object as the first argument. For service workers, you would pass navigator.serviceWorker.controller (checking for null beforehand). For web workers, you would pass the instance of your worker.

// In your main thread
import { sendRequest } from 'worker-request-response';
import { yourWorker } from './somewhere';

async function() {
  const response = await sendRequest<number, string>(
    yourWorker
    42,
  );
}

Asynchronous request handler in the worker

The request handler that you pass into handleRequestsWith can be synchronous or asynchronous — in the latter case the resulting promise is awaited before being sent back.

License

The source code of this project is distributed under the terms of the ISC license. It's like MIT, but better. Click here to learn what that means.

About

A Promise API for submitting requests to workers and tracking responses.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published