I'm currently trying to spawn a child process to handle some POST data with NodeJS (using Koa framework).
Ideally, I would like to wait for the child process to finish before redirecting, but since the child process is asynchronous, the code always redirects first. I've been trying to fix this for a long time and came up with a couple hackish ways to partially solve it, but nothing very clean or usable.
What is the best way to handle this?
Below is the function for my post route (using koa-route middleware).
function *task() {
var p = spawn("process", args);
p.on("data", function(res) {
// process data
});
p.stdin.write("input");
this.redirect('/'); // wait to execute this
}
To wait for an synchronous task/something to be done in koa, you have to yield
a function that takes a callback argument. In this case to wait for the child process to be done, you have for the "exit" event to be emitted. Though you can also listen for other child process events like close
or end
event of stdout. They are emitted before exit.
So in this case yield function (cb) { p.on("exit", cb); }
should work which we can reduce it to yield p.on.bind(p, "exit");
using Function::bind
function *task() {
var p = spawn("process", args);
p.on("data", function(res) {
// process data
});
p.stdin.write("input");
yield p.on.bind(p, "exit");
this.redirect('/'); // wait to execute this
}
You can also use a helper module to help you: co-child-process
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments