等待CasperJS中的子进程 [英] Wait for a child process in CasperJS

查看:71
本文介绍了等待CasperJS中的子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个加载某些页面的CasperJS进程,然后需要调用go-process来分析页面并决定接下来要加载哪个页面。 go-process需要一段时间才能执行。我的问题是CasperJS不会等待go-process完成并退出。

I have a CasperJS process that loads some page and then it needs to call a go-process to analyze the page and to decide what page should be loaded next. go-process takes a while to execute. My problem is that CasperJS doesn't wait for the go-process to complete and exits.

casper.then(function(){
  var p = cp.execFile('/path/parse', [], {}, function(error, stdout, stderr) {
    console.log(stdout);
  });

});

我如何等待子进程完成?

How can I wait for my child process to complete?

推荐答案

所有然后* 等待* 函数正在安排要执行的步骤。当CasperJS用完执行步骤并且没有函数传递到 casper.run()时,它将自动退出。

All then* and wait* functions are scheduling steps to be executed. When CasperJS runs out of steps to execute and no function is passed into casper.run(), then it will automatically exit.

简单的解决方法是始终将空函数传递给 casper.run()并从函数内部安排新步骤:

The easy fix would be to always pass an empty function into casper.run() and schedule new steps from inside the function:

casper.then(function(){
  var p = cp.execFile('/path/parse', [], {}, function(error, stdout, stderr) {
    console.log(stdout);
    casper.thenOpen(parsedUrl).then(function(){
      // do something on page
    });
  });
});
casper.run(function(){});

更简洁的方法是编写自己的步骤函数来包装 execFile function:

A more clean approach would be to write your own step function that wraps the execFile function:

casper.waitForFileExec = function(process, callback, onTimeout, timeout){
    this.then(function(){
        var cp = require('child_process'),
            finished = false,
            self = this;
        timeout = timeout === null || this.options.stepTimeout;
        cp.execFile(process, [], {}, function(error, stdout, stderr) {
            finished = true;
            callback.call(self, error, stdout, stderr);
        });
        this.waitFor(function check(){
            return finished;
        }, null, onTimeout, timeout);
    });
    return this; // for builder/promise pattern
};

...
casper.waitForFileExec('/path/parse', function(error, stdout, stderr) {
    this.echo(stdout);
    this.thenOpen(parsedUrl).then(function(){
        // do something on page
    });
}).run();

这篇关于等待CasperJS中的子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆