2.0.1 • Published 8 months ago

define-threads v2.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

define-threads

Zero dependencies, helps you use worker more easily in NodeJS, just like an async function.

Our implementation principle is very simple and clever, so you don't need to worry about introducing too many third-party libraries that would make your project bloated. If you want to understand how this library works, you can read the src/index.ts file.

Installation

npm install define-threads

Usage

// my-worker.ts

import { createThreadContext } from "define-threads";

// Create a thread context using the current file path
const defineThread = createThreadContext(__filename);

// Thread Function 1
export const calculateLargeSum = defineThread(async (maxNumber: number) => {
  let sum = 0;
  for (let i = 0; i < maxNumber; i++) {
    sum += i;
  }
  return sum;
});

// Thread Function 2
export const testFunction = defineThread(
  async (a: number, b: number, c: number) => {
    return a + b + c;
  }
);
// index.ts

import { calculateLargeSum, testFunction } from "./my-worker";

async function main() {
  // Use them like a simple async function
  // TS type hint is complete!
  const sum = await calculateLargeSum(100);
  console.log(sum); // Output: 4950

  // call Thread Function 2
  const responses = await testFunction(1, 2, 3);
  console.log(responses); // Output: 6
}

main();

Report bug

The code has been tested locally and no issues were found. If you encounter any bugs while using it, please create an issue.

License

MIT License

2.0.1

8 months ago

2.0.0

8 months ago

1.0.2

8 months ago

1.0.1

8 months ago