npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

promise-workers

v2.0.2

Published

Promises + Workers = multi-threaded PromiseWorkers!

Downloads

24

Readme

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