问题描述
计算需要很多时间,所以我使用了 fork 过程,面对来自数据处理器的消息的困难,我需要发送我的计算值作为响应,但为什么总是得到声明的变量 totalSum空白。检查以下语法。
app.js
const cluster = require("cluster");
const { fork } = require("child_process");
const path = require("path");
exports.get_company_total_sum = async (req,res,next) => {
try {
const { hs_object_id: companyId,hs_parent_company_id } = req.query;
//const companyId = hs_object_id;
console.log("hs_object_id",companyId);
const processpath = path.join(
__dirname,"..","9-services","tierone_carrier_dataProcess.js"
);
let totalSum = "";
const child = fork(processpath);
child.send({ companyId });
//process the messages coming from the task processor
child.on("message",(response) => {
console.log("response::",response.result);
//return res.json({ message: response.message });
totalSum = response.result;
});
//remove prevIoUsly openned node instance when we finished
child.on("close",function (msg) {
this.kill();
});
return res.json({ "total sum": totalSum });
};
tierone_carrier_dataProcess.js
process.on("message",(payload) => {
if (payload.companyId !== "") {
const sum = longcomputation(payload);
process.send({ result: sum });
process.disconnect();
}
});
function longcomputation(payload) {
let sum = 0;
for (let i = 0; i < payload.companyId; i++) {
sum += i;
}
return sum;
}
process.on("uncaughtException",function (err) {
console.log("Error happened: " + err.message + "\n" + err.stack + ".\n");
console.log("Gracefully finish the routine.");
});
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)