问题
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