简体   繁体   English

等待异步过程完成,然后再重定向到Koajs

[英]Wait for async process to finish before redirect in koajs

I'm currently trying to spawn a child process to handle some POST data with NodeJS (using Koa framework). 我目前正在尝试生成一个子进程来使用NodeJS(使用Koa框架)处理一些POST数据。

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). 以下是我发布路线的功能(使用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
}

To wait for an synchronous task/something to be done in koa, you have to yield a function that takes a callback argument. 为了等待在koa中完成同步任务/操作,您必须yield一个带有回调参数的函数。 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. 虽然您也可以侦听其他子进程事件,例如close或标准输出的end事件。 They are emitted before exit. 它们在退出之前发出。

So in this case yield function (cb) { p.on("exit", cb); } 因此,在这种情况下, yield function (cb) { p.on("exit", cb); } yield function (cb) { p.on("exit", cb); } should work which we can reduce it to yield p.on.bind(p, "exit"); yield function (cb) { p.on("exit", cb); }应该起作用,我们可以减少它yield p.on.bind(p, "exit"); using Function::bind 使用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 您还可以使用帮助程序模块来帮助您: 共同子过程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM