Hassan Amir
Hassan Amir

Reputation: 189

how to pass function output to another function

was playing around with casperjs lately and didnt manage to complete the below code, was using child_process and need to get function output to be passed to another function any ideas ?

success call variable scope limited to success function only, and i cant use it anywhere in my code

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
    })
}

Upvotes: 1

Views: 125

Answers (1)

Artjom B.
Artjom B.

Reputation: 61892

Since spawn is an asynchronous process, you need to use a callback for testvalue. Returning something inside the event handler doesn't return it from testvalue.

The other problem is that you need to remain in the CasperJS control flow. This is why I use testvaluedone to determine if the spawned process is done executing and I can 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;
    });
}

Upvotes: 1

Related Questions