how to show async data in UI

╄→гoц情女王★ 提交于 2020-01-06 05:30:08

问题


I wrote an async function that needs to call a program in the server and that program generate a file which needs to load in UI for displaying. I am not sure how to show the result in my UI since execFile is async function and it may take few second results to be ready?

Do I need to have kind of infinity loop to check the result is ready in the server?

I am using nodejs-express handlebars.

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

diagram of what I want to do.


回答1:


Avoid polling whenever possible. Sometimes you can't avoid it, but here you can. Just make use of the event handlers to find out what the state of the process is. You can register handlers for the following related events:

  • disconnect
  • error
  • close
  • message

An example of usage is:

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

For more information, see this detailed explanation on freeCodeCamp's website (not affiliated).



来源:https://stackoverflow.com/questions/53694567/how-to-show-async-data-in-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!