Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Goroutines in Node with Worker Threads
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
You can’t perform that action at this time.