1.2.0 • Published 6 months ago

assist-worker v1.2.0

Weekly downloads
-
License
MIT
Repository
-
Last release
6 months ago

AssistWorker

providing minimal APIs to allow you to use Web Workers more flexibly in your code.

Installation

npm i -S assist-worker
# or
pnpm add assist-worker

Usage

create(job)

create and initialize worker threads。

@param {function} job - the function that needs to be put into the worker thread to execute

@returns {object} the object used to control worker thread execution and thread shutdown

Example

import { createAssistWorker } from "assist-worker";

const job = (param, workerMethods) => {
  console.log(param); // PARAM TO WORKER
};

const worker = createAssistWorker().create(job);

// execute the job in the worker thread
await worker.run('PARAM TO WORKER');

// shutdown worker thread
await worker.terminate();

onMessage(callback)

receive and process the message sent by the worker thread。

@param {function} callback - the callback for the worker thread to send information to the main thread

@returns {object} assistWorker

Example

import { createAssistWorker } from "assist-worker";

const job = (workerMethods) => {
  // take out the method in the object containing the worker thread internal control method
  const { postMessage } = workerMethods;
  // send message to the main thread
  postMessage('MESSAGE TO MAIN')
};

const worker = createAssistWorker()
  // the main thread receives and processes message
  .onMessage((message) => {
      console.log(message); // MESSAGE TO MAIN
  })
  .create(job);

await worker.run();

collect(data)

collect the main thread data that needs to be used in the worker thread.

@param {object} data - the main thread data used in the worker thread

@returns {object} assistWorker

Example

import { createAssistWorker } from "assist-worker";

const numbers = [1, 2, 3, 4, 5];
const sum = (arr) => arr.reduce((total, i) => total + i, 0);

const worker = createAssistWorker()
  .collect({ numbers, sum })
  .create(({ collections }) => {
    const { numbers, sum } = collections;
    console.log(sum(numbers)); // 15
  });

await worker.run();

❗Caveat

the data collected here only supports serializable data limited by web workers itself。

However, functions are supported here, but it is necessary to ensure that the main thread variables referenced in the function body are also collected, for example:

...
const id = 1;

const test = () => {
  console.log(id);
});

assistWorker.collect({ test })     // ✖️ ReferenceError: id is not defined
assistWorker.collect({ id, test }) // ✔️
...
1.2.0

6 months ago

1.1.1

6 months ago

1.0.2

2 years ago

1.1.0

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago