Bizon
Bizon is a simple library that allows you to run functions in a worker thread of Node.JS.
Installation
npm i --save bizon
Basic usage
const function$ = ; void { // Initialize your own thread function const multiply$ = ; // Then call the function and get a result. Your thread function returns a promise const result = await multiply$(10, 20); console.log(result); // 30};
Using imports
const function$ = ;const fs = ; void { // You can use required modules of the parent thread const readFile$ = ; // The function will be async, because it will be run in a thread const result = await readFile$('./index.js'); console.log(result);};
'this' in a thread function
You can use 'this' context
const function$ = ; name = null; ;} void { const person = ; console; // null await person; console; // Bob};
Arguments
You can pass numbers, strings, arrays, objects and functions to the arguments
const function$ = ; void { // You can create the thread map! // You can pass a callbacks to arguments of a thread function Arrayprototype; const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // Just call map$ like the sync map function of an array const result = await numbers.map$((val, i) => { return val ** i; }); console;};
Recursive calls
You can call your function recursively
const function$ = ; void { // For recursively call you need to pass named function expression as callback const fib$ = ; const result = await fib$(40); console.log(result) // 102334155};
Restrictions
You can not get access to variables defined outside the function
const function$ = ; const a = 10; const func$ = ; func$().then(result => console.log(result)); // Error: ReferenceError: a is not defined
You can not return objects and arrays with promises and functions
const function$ = ; const func$ = ; func$().then(result => console.log(result)); // Error: DataCloneError: #<Promise> could not be cloned.
You can not return functions
const function$ = ; const func$ = ;func$().then(result => console.log(result)); // Error: DataCloneError: function () {// return 'hello';// } could not be cloned.