如何将函数输出传递给另一个函数
问题描述:
最近和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
})
}
答
由于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;
});
}
+0
这项工作。谢谢 – 2014-09-07 10:47:08
+0
我将实际的调用添加到'testvalue'。 – 2014-09-07 11:06:08
是因为数据它作为函数的参数作为范围的一部分。如果你返回类似于'return {json:JSON.stringify(data),data:data}'的东西,这将使得函数返回一个包含两者的对象,这样你就可以访问这个范围之外的数据。 – GillesC 2014-09-06 19:31:46
这没有为我工作,你能提供完整的例子吗? – 2014-09-06 23:08:19