The question is formalized as this.
Can we call a non-pure function in another thread in javascript and get a Promise?
One possible implementation of this feature is.
function executeAsync(f: function, ...args);
1. Javascript runtime spawns 1 parallel unit (thread, coroutine, etc).
2. Javascript runtime executes the function f in parallel. (Ignore data race issue, maybe add mutex later)
3. After the parallel unit has done its job. Remove the parallel unit from the pool and resolve the Promise. (put callback into the callback queue)
Please comment if you still have any doubt. Thanks
FOR REFERENCES
The code below I implemented serves the similar purpose but it doesn't work for non-pure function
It uses safe-eval
node module that evaluates a string and convert to javascript function
const {isMainThread, Worker, workerData, parentPort} = require("worker_threads");
const {safeEval} = require("safe-eval");
if (isMainThread) {
// functionObject must be pure function
module.exports = {executeAsync: function(functionObject = function(...paramsObject) {return undefined;}, ...paramsObject) {
return new Promise(function(resolve, reject) {
const worker = new Worker(__filename, {
workerData: {
functionString: functionObject.toString(),
argumentsObject: paramsObject,
}
});
worker.on("message", resolve);
worker.on("error", reject);
worker.on("exit", function(functionObject) {
if (functionObject != 0) {
reject(new Error(`Worker stopped with code ${functionObject}`));
}
});
});
}};
} else {
const {functionString, argumentsObject} = workerData;
const functionObject = safeEval(functionString);
parentPort.postMessage(functionObject(...argumentsObject));
}