With this library, you can create a Promise that executes in a new thread.
npm install wormisePromise.
wormise вы можете получить удобный интерфейс-обертку для работы с вычислениями в новом потоке.
wormise(executedFunction, dir, params): Promise
dir - папка в которой выполняется вызов wormise
executedFunction - функция, выполняемая в отдельном потоке.
params - параметры для _executedFunction_
wormise/esm) и CJS (wormise/cjs).
Promise.
wormise, you can get a convenient wrapper interface to work with computations in a new thread.
wormise/esm) and CJS (wormise/cjs).
wormise(executedFunction, dir, params): Promise
dir - the folder where the wormise call is made.
executedFunction - function executed in a separate thread.
params - arguments for _executedFunction_
typescript
import wormise, { wormiseDafaultDirname } from 'wormise/esm';
const dir = wormiseDafaultDirname(import.meta.url);
async function getCalculationsResult() {
try {
const result = await wormise(
params => {
// Complicated calculations
return new Date(params);
},
dir,
Date.now(),
);
console.log(result);
} catch (error) {
console.error(error);
}
}
getCalculationsResult();
`
$3
`typescript
import wormise, { wormiseDafaultDirname } from 'wormise/esm';
const dir = wormiseDafaultDirname(import.meta.url);
import { threadId } from 'worker_threads';
console.log({ threadId });
const data = wormise(
async () => {
const logWormiseThreadId = async () => {
const { threadId } = await import('worker_threads');
console.log({ threadId });
};
await logWormiseThreadId();
},
dir,
undefined,
);
// Output:
// { threadId: 0 }
// { threadId: 1 }
`
Example tsconfig.json
`json
{
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"skipLibCheck": true,
"moduleResolution": "NodeNext",
"noEmitHelpers": true,
"outDir": "dist"
}
}
`
Using in CommonJS
Just import from wormise/cjs like this:
`typescript
import wormise, { wormiseDafaultDirname } from 'wormise/cjs';
async function getCalculationsResult() {
try {
const result = await wormise(
params => {
// Complicated calculations
return new Date(params);
},
__dirname,
Date.now(),
);
console.log(result);
} catch (error) {
console.error(error);
}
}
getCalculationsResult();
``