Created
October 12, 2018 16:30
-
-
Save felixfbecker/4eab0b380a2c34e5b33abf39c967568f to your computer and use it in GitHub Desktop.
Goroutines in Node with Worker Threads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Worker } from 'worker_threads' | |
export function work<P extends any[], R>(script: (...args: P) => R | PromiseLike<R>, ...args: P): Promise<R> { | |
return new Promise((resolve, reject) => { | |
const workerSource = ` | |
const { workerData, parentPort } = require('worker_threads'); | |
Promise.resolve((${script})(...workerData)) | |
.then(result => { | |
parentPort.postMessage({ type: 'success', result }) | |
}, error => { | |
parentPort.postMessage({ type: 'error', error }) | |
}); | |
` | |
const worker = new Worker(workerSource, { eval: true, workerData: args }) | |
worker.on('message', (message: { type: 'success' | 'error'; value: any }) => { | |
if (message.type === 'success') { | |
resolve(message.value) | |
} else { | |
reject(message.value) | |
} | |
}) | |
}) | |
} | |
async function test() { | |
const interval = setInterval(() => { | |
console.log('Im not blocked!') | |
}, 500) | |
const result = await work(async (to: number) => { | |
// CPU bound activity | |
let i = 0 | |
console.log('start counting to', to) | |
while (i < to) { | |
i++ | |
} | |
return i | |
}, 10000000000) | |
console.log('the result is', result) | |
clearInterval(interval) | |
} | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment