Skip to content

Instantly share code, notes, and snippets.

@alekstar79
Created June 25, 2023 17:17
Show Gist options
  • Save alekstar79/6ac001d5f508562e806ef1ba0e32b429 to your computer and use it in GitHub Desktop.
Save alekstar79/6ac001d5f508562e806ef1ba0e32b429 to your computer and use it in GitHub Desktop.
/** @see https://gist.github.com/alekstar79/11125248f8dc609f5c8dcba3e0f75b5e */
import { createCachedFunction } from './cached.mjs'
/** @see https://gist.github.com/alekstar79/042a211b62203f1439f2012ce6aa9f55 */
import { workerInit } from './worker.mjs'
/**
* @param {function} worker
* @return {function(*=): Promise<unknown>}
* @example
*
* const run = createCachedWorker(({ data: num }) => {
* const calcFibonacci = n => n <= 1 ? n : calcFibonacci(n - 1) + calcFibonacci(n - 2)
* self.postMessage({ num, fib: calcFibonacci(num) })
* self.close()
* })
*
* Promise.resolve()
* .then(() => run(10))
* .then(result => { console.info('worker with arg 10 finished', result) })
* .catch(e => { console.log('web worker failed: ', e.message) })
* .then(() => run(20))
* .then(result => { console.info('worker with arg 20 finished', result) })
* .catch(e => { console.log('web worker failed: ', e.message) })
* .then(() => run(30))
* .then(result => { console.info('worker with arg 30 finished', result) })
* .catch(e => { console.log('web worker failed: ', e.message) })
*/
export function createCachedWorker(worker)
{
return createCachedFunction(workerInit(worker))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment