【发布时间】:2021-03-14 02:51:19
【问题描述】:
我已经尝试在节点中分叉。对于简单的计算,它似乎工作正常。但是当我使用 for 循环时,我没有得到任何结果。我也尝试过使用promise,但我得到的只是promise pending。以下是使用的代码。
在 moduleProgress.js 中:
const getModules = async (studentArray) => {
let progress = [];
for (const student of studentArray) {
console.log(student); //prints the first student id an then nothing happens
let std = await User.findById(student); //stops here
console.log(std); //nothing
std = {
username: std.username,
firstname: std.firstname,
lastname: std.lastname,
batch: std.batch,
};
progress.push(std);
}
return progress;
};
process.on("message", async (params) => {
const progress = await getModules(params.students);
process.send(progress);
});
在另一个文件中:
if (students.length > 0) {
const calculation = fork("helpers/moduleProgress.js");
calculation.send({
students: students,
});
calculation.on("message", (response) => {
allStatus = response;
console.log(response)
});
res.json({
success: true,
allProgress: allStatus,
});
【问题讨论】:
-
我认为你应该考虑使用 fork。 stackoverflow.com/questions/17861362/…
-
@SrinathNilatech 我用过叉子。还是我做错了什么?
-
您是在尝试运行子进程还是只想从 helpers/moduleProgress.js 中的另一个文件运行函数?
-
@SrinathNilatech 我正在尝试运行一个子进程。
-
我可以知道在哪里调用了 fork,因为您只共享了一个单独的代码。如果你能在 github 或 stackblitz 上分享代码就太好了
标签: node.js async-await child-process