nanothreads
nanothreads copied to clipboard
document how to use functions & imported stuff from InlineThreads
People will want to be able to use functions from outside the context of an inlineThread
import { InlineThread } from 'nanothreads'
import _ from 'lodash'
export function randomQuestion(): string {
return _.sample(['how are you', 'aaa', 'bbb', 'ccc'])
}
const inlineThread = new InlineThread<[name: string], string>((name) => {
return `hello ${name}! ${randomQuestion()}`
}, {})
console.log(await inlineThread.send('AAA'))
but it doesn't work
$ bun test.ts
200 | #onClose(e) {
201 | this.#onExitPromise = e.code, this.emit("exit", e.code);
202 | }
203 | #onError(event) {
204 | let error = event?.error;
205 | error = new Error(event.message, { cause: event });
^
error: 1 | const H=async(...a)=>((name) => {
2 | return `hello ${name}! ${randomQuestion()}`;
^
ReferenceError: Can't find variable: randomQuestion
at blob:006c7714-3aae-4b3c-bf05-7e71803f3848:2:28
at H (blob:006c7714-3aae-4b3c-bf05-7e71803f3848:1:18)
at blob:006c7714-3aae-4b3c-bf05-7e71803f3848:3:25
cause: {
"isTrusted": true
}
I achieved a horrid way of doing this with concurrent.js with
/**
* Creates a threaded version of a given function.
* @param {Function} func - The original function to be executed on another thread.
* @param {string} funcFile - The file path or URL of the module containing the original function. `import.meta.url` in most cases
*/
export function asThreaded<I extends any[], O>(func: (...args: I) => O, funcFile: string): (...args: I) => Promise<O> {
concurrent.config({ maxThreads: availableParallelism() })
const concurrentThis = concurrent.import(funcFile)
return async function (...args: I): Promise<O> {
return ((await concurrentThis.load() as Record<string, Function>)[func.name])(...args) as Promise<O>
}
}
export function toBeThreaded(...): ... {
...
}
const threadedFunc = asThreaded(obstructionTest, import.meta.url)
but I was hoping I could use this library to dodge that nonsense