Wait for async process to finish before redirect in koajs

若如初见. 提交于 2019-12-10 00:42:45

问题


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
}

回答1:


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



来源:https://stackoverflow.com/questions/23852948/wait-for-async-process-to-finish-before-redirect-in-koajs

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