编辑:
回答您的编辑。我现在看到了意图。如果它在 nodejs 中运行,您可以使用 worker_thread 来处理 https://nodejs.org/api/worker_threads.html#worker_threads_worker_workerdata。
例如:
// main.js
const runCode = (code) => {
const worker = new Worker("./code-executor.js", { workerData: { code: guestCode } });
const promise = new Promise((resolve) => {
setTimeout(() => worker.kill(), 60000 * 5);
worker.on("error", () => {
return reject(new SomeCustomError())
});
worker.on("message", (message) => {
if(message.success) return resolve(message.result);
return reject(new Error(message.error));
});
});
promise.finally(() => { worker.kill() });
return promise;
}
// code-executor.js
const { workerData, parentPort } = require("worker_threads");
const { code } = workerData;
Promise.resolve()
.then(() => (new Function(fcode))())
.then((result) => {
parentPort.postMessage({
success: true,
result: value
})
})
.catch((error) => {
parentPort.postMessage({
success: true,
error: error.message
})
});
如果在浏览器中https://developer.mozilla.org/en-US/docs/Web/API/Worker
WebAPI不完全一样,但逻辑应该差不多
原创
杀死一个进程。另请阅读:https://nodejs.org/api/process.html#process_signal_events
process.kill(pid, "SIGINT")
“杀死”一个长时间运行的函数,你得破解一下。没有优雅的解决方案。注入一个控制器,它可以在长时间运行的函数之外发生变异。要从外部阻止它,请设置controller.isStopped = true
export const STOP_EXECUTION = Symbol();
function longRunning(controller){
... codes
// add stopping point
if(controller.isStopped) throw STOP_EXECUTION;
... codes
// add stopping point
if(controller.isStopped) throw STOP_EXECUTION;
... codes
}
// catch it by
try{
longRunnning();
}catch(e){
switch(true){
e === STOP_EXECUTION: ...; // the longRunning function is stopped from the outside
default: ...; // the longRunning function is throwing not because of being stopped
}
}
要点:https://gist.github.com/Kelerchian/3824ca4ce1be390d34c5147db671cc9b