等待异步过程完成

等待异步过程完成

本文介绍了等待异步过程完成,然后再重定向到Koajs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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
}

推荐答案

要在koa中等待同步任务/事情完成,您必须yield一个带有回调参数的函数.在这种情况下,要等待子进程完成,您必须进行退出"事件被发射.尽管您也可以侦听其他子进程事件,例如stdout的closeend事件.它们在退出前发出.

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.

因此在这种情况下,yield function (cb) { p.on("exit", cb); }应该可以工作,我们可以使用yield p.on.bind(p, "exit"); /Function/bind"rel =" nofollow> Function::bind

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
}

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

You can also use a helper module to help you: co-child-process

这篇关于等待异步过程完成,然后再重定向到Koajs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:48