如何将函数输出传递给另一个函数

时间:2014-09-06 19:27:36

标签: javascript casperjs

最近玩casperjs并没有设法完成下面的代码,使用child_process并需要将函数输出传递给另一个函数的任何想法?

成功调用变量范围仅限于成功函数,我无法在我的代码中的任何地方使用它

casper.repeat(3, function() {
    this.sendKeys(x('//*[@id="text-area"]'), testvalue.call(this)); //  testvalue.call(this) dosnt input anything here
})

casper.echo(testvalue.call(this)); // Print output successfully

function testvalue() {
    var spawn = require("child_process").spawn
    var execFile = require("child_process").execFile
    var child = spawn("/usr/bin/php", ["script.php"])

    child.stdout.on("data", function (data) {
        console.log(JSON.stringify(data)); // Print output successfully
        return JSON.stringify(data); // Problem is here i cant use Data any where in code except this scope
    })
}

1 个答案:

答案 0 :(得分:1)

由于spawn是异步过程,因此您需要对testvalue使用回调。返回事件处理程序内的某些内容不会从testvalue返回它。

另一个问题是您需要保留在CasperJS控制流中。这就是我使用testvaluedone来确定生成的进程是否已完成执行的原因,我可以completeData

casper.repeat(3, function() {
    var testvaluedone = false;
    var completeData = "";
    testvalue();
    this.waitFor(function check(){
        return testvaluedone;
    }, function then(){
        this.sendKeys(x('//*[@id="text-area"]'), completeData);
    }); // maybe tweak the timeout a little
});

var testvaluedone, completeData;
function testvalue() {
    var spawn = require("child_process").spawn;
    var execFile = require("child_process").execFile;
    var child = spawn("/usr/bin/php", ["script.php"]);

    child.stdout.on("data", function (data) {
        completeData += JSON.stringify(data);
    });
    child.on("exit", function(code){
        testvaluedone = true;
    });
}
相关问题