Created
September 17, 2019 15:51
-
-
Save lac5/5a8c122738cd5d64668cf2e68ef0cc24 to your computer and use it in GitHub Desktop.
`worker_thread` example
This file contains 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
/** | |
* @file This creates a worker thread that only handles template rendering. | |
* The purpose is to keep the main thread free so that processes like | |
* rendering don't block the event loop. | |
*/ | |
const { | |
Worker, isMainThread, parentPort | |
} = require('worker_threads'); | |
if (isMainThread) { | |
const worker = new Worker(__filename); | |
exports.render = function(template, data) { | |
return new Promise((resolve, reject) => { | |
const id = Date.now() + Math.random(); | |
worker.postMessage({ id, template, data }); | |
function onmessage(response) { | |
if (response.id === id) { | |
if (response.error) { | |
reject(response.error); | |
} else { | |
resolve(response.data); | |
} | |
worker.off('message', onmessage); | |
} | |
} | |
worker.on('message', onmessage); | |
setTimeout(function() { | |
reject(new Error('Timeout exceeded. Try again in a few seconds.')); | |
worker.off('message', onmessage); | |
}, 15000); | |
}); | |
}; | |
} else { | |
const Handlebars = require('handlebars'); | |
parentPort.on('message', function(request) { | |
try { | |
const data = Handlebars.compile(request.template)(request.data); | |
parentPort.postMessage({ id: request.id, data }); | |
} catch (error) { | |
parentPort.postMessage({ id: request.id, error }); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment