Giter VIP home page Giter VIP logo

promise-workers's Introduction

Promise Workers

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.

Usage

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

API

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 local workerData 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.

interface PromiseWorkerOptions<T = any>

  • 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.

PromiseWorker.all(values: any[]): Promise<any[]>

Calls Promise.all for convenience and Promise API completeness.

PromiseWorker.allSettled(values: any[]): Promise<any[]>

Calls Promise.allSettled for convenience and Promise API completeness.

PromiseWorker.race(not_implemented_or_recommended: never): Error

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.

PromiseWorker.reject(reason: any): Promise

Calls Promise.reject for convenience and Promise API completeness.

PromiseWorker.resolve(value?: any): Promise

Calls Promise.resolve for convenience and Promise API completeness.

Supported Platforms and Differences

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.

Difference In Behavior

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.

Differences In Features

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

Contributors

  • Aaron Huggins

promise-workers's People

Contributors

aaronhuggins avatar ahuggins-nhs avatar

Stargazers

 avatar Ustym Ukhman avatar Juan P. Prieto avatar Cody Nova avatar Jasper avatar

promise-workers's Issues

Great idea

Exposing the worker process via Promise is really a great idea and this is exactly what I am looking for. Surprisingly this module isn't very popular. Interesting.

The example is not working

I tried run the example but it is not working at all. Refer to the following for the running log.

➜  util cat worker.js
const { PromiseWorker } = require('promise-workers');

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);
    return result;
  } catch (error) {
    console.log(error)
    throw error;
  }
}

main().then(console.log).catch(console.error);
➜  util node worker.js
➜  util npm -v
6.14.12
➜  util node -v
v14.16.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.