我目前正在尝试生成一个子进程来使用NodeJS(使用Koa框架)处理一些POST数据。

理想情况下,我想在重定向之前等待子进程完成,但是由于子进程是异步的,因此代码始终首先重定向。我一直在尝试修复此问题很长时间,并想出了几种新颖的方法来部分解决它,但是没有什么非常干净或可用的。

处理此问题的最佳方法是什么?

以下是我发布路线的功能(使用koa-route中间件)。

function *task() {
        var p = spawn("process", args);
        p.on("data", function(res) {
                // process data
        });

        p.stdin.write("input");

        this.redirect('/'); // wait to execute this
}

最佳答案

为了等待在koa中完成同步任务/操作,您必须yield一个带有回调参数的函数。在这种情况下,要等待子进程完成,必须发出"exit" event。虽然您也可以侦听其他子进程事件,例如stdout的closeend事件。它们在退出之前发出。

因此,在这种情况下yield function (cb) { p.on("exit", cb); }应该可以工作,我们可以使用yield p.on.bind(p, "exit");将其减小为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
}


您还可以使用帮助程序模块来帮助您:co-child-process

10-05 18:42
查看更多