0

我编写了一个异步函数,该函数需要调用服务器中的程序,并且该程序会生成一个文件,该文件需要加载到 UI 中进行显示。我不确定如何在我的 UI 中显示结果,因为 execFile 是异步函数,可能需要几秒钟的时间才能准备好结果?

我是否需要有一种无限循环来检查服务器中的结果是否准备就绪?

我正在使用 nodejs-express 车把。

router.post('/',function(req, res, next) {
  const child = execFile('program.exe', ['in.sql'], (error, stdout, stderr) => {
      if (error) 
      {
        console.log(error);
        return error;
      }
      else
      {
        // TODO: how to send the result to UI?
        console.log(stdout);
      }
    });
    return res.sendStatus(200);
});

我想做什么的图表。 在此处输入图像描述

4

1 回答 1

-1

尽可能避免轮询。有时你无法避免它,但在这里你可以。只需使用事件处理程序来找出进程的状态。您可以为以下相关事件注册处理程序:

  • 断开
  • 错误
  • 信息

一个使用示例是:

child.on('exit', function (code, signal) {
  console.log('child process exited with ' +
              `code ${code} and signal ${signal}`);
});

有关更多信息,请参阅freeCodeCamp 网站(非附属网站)上的详细说明。

于 2018-12-10T22:31:42.880 回答