如何解决为什么在 fork 处理来自数据处理器的消息总是空白
计算需要很多时间,所以我使用了 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 举报,一经查实,本站将立刻删除。