代码之家  ›  专栏  ›  技术社区  ›  Amir

如何在ui中显示异步数据

  •  0
  • Amir  · 技术社区  · 7 年前

    我写了一个异步函数,需要调用服务器中的程序,该程序生成一个文件,需要加载到ui中显示。我不知道如何在我的ui中显示结果,因为execfile是异步函数,可能需要几秒钟的时间才能准备好结果?

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

    我用的是nodejs快速车把。

    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);
    });
    

    我想做什么的图表。 enter image description here

    1 回复  |  直到 7 年前
        1
  •  -1
  •   Andre M    7 年前

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

    • 断开
    • 错误
    • 关闭
    • 消息

    用法示例如下:

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

    有关详细信息,请参见 this detailed explanation 在Freecodecamp的网站上(不附属)。