【问题标题】:Wait for async process to finish before redirect in koajs在 koajs 重定向之前等待异步进程完成
【发布时间】:2014-07-14 05:07:23
【问题描述】:

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

理想情况下,我希望在重定向之前等待子进程完成,但由于子进程是异步的,因此代码总是首先重定向。很长时间以来,我一直在尝试解决这个问题,并想出了一些骇人听闻的方法来部分解决它,但没有什么非常干净或可用。

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

以下是我的 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
}

【问题讨论】:

    标签: javascript node.js koa


    【解决方案1】:

    要在 koa 中等待同步任务/某事完成,您必须 yield 一个接受回调参数的函数。在这种情况下,要等待子进程完成,您必须发出 "exit" event。尽管您也可以监听其他子进程事件,例如标准输出的closeend 事件。它们在退出之前发出。

    所以在这种情况下yield function (cb) { p.on("exit", cb); } 应该可以工作,我们可以使用Function::bind 将其减少到yield p.on.bind(p, "exit");

    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

    【讨论】:

    • 太棒了!非常感谢。
    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2010-10-11
    • 2011-02-15
    相关资源
    最近更新 更多