在nodejs中使用fork wait不工作

xzlaal3s  于 12个月前  发布在  Node.js
关注(0)|答案(2)|浏览(112)

我已经试过分叉了。对于简单的计算,它似乎工作得很好。但是当我使用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,
        });
0x6upsns

0x6upsns1#

解决了。在moduleProgress.js(child)中调用mongoose的示例,它就像一个魅力一样工作。

lc8prwob

lc8prwob2#

我真的不理解公认的解决方案,但我带着类似的问题来到这里,关于如何创建一个fork,发送一个请求,设置如何处理响应,然后等待直到完成。
对于我的解决方案,我的子进程代码(示例中的moduleProgress.js)看起来是一样的,但是在产生我使用的fork的父进程中,await与once()侦听exit事件,然后在函数中侦听消息,我在处理完子进程后调用了kill()。我已经更新了这个例子,根据上下文填充了一些细节,比如方法参数:

const { fork } = require('child_process');
const { once } = require('events');

exports.calculateProgress = async (req, res) => {
  const { students } = req;

  if (students.length > 0) {
    const calculation = fork("helpers/moduleProgress.js");
    calculation.send({
      students: students,
    });
    calculation.on("message", (response) => {
      allStatus = response;
      console.log(response)
      calculation.kill(); // Kill the child
    });
    await once(calculation, 'exit'); // Wait for the child to exit
    res.json({
      success: true,
      allProgress: allStatus,
    });
  }
}

我不认为这是给定示例的最佳解决方案,因为看起来你可能只需要在消息事件侦听器中调用res.json(),但它解决了等待子进程给出响应的问题。
我的用例最初是使用子进程异步进行计算,但后来我想添加像计时器这样的指标,可以与父进程中的其他指标结合使用,因此能够使用await就派上用场了。

相关问题