从casperjs waitFor()返回数据

时间:2014-08-17 14:02:38

标签: javascript casperjs

我想对waitFor的结果有一个指示。请考虑以下代码:

var success = false;
casper.waitFor(function check(){
    return isSuccess();
},function then(){
    casper.echo("Great succees");
    success = true;
},function fail(){
    casper.echo("Failure");
},2000);
console.log("Did we make it? "+success);

不幸的是,即使then()执行,全局success似乎超出范围,也不会更新为true。我也考虑过让waitFor返回这个标志,但是这个函数似乎返回了一个casper对象。

想法?

1 个答案:

答案 0 :(得分:2)

所有wait*函数以及所有then*函数都是步进函数。这意味着调度了传递的回调函数的执行。它们本质上是异步的。

当您在另一个步骤函数回调中调用waitFor(或任何其他步骤函数)时,将调度这些函数在当前步骤函数结束时执行。这意味着如果您调用异步waitFor,然后调用同步console.log,则结果将不会就绪。

casper.then(function(){
    var success = false;
    casper.waitFor(check, function then(){
        casper.echo("Great success");
        success = true;
    }, onTimeout, 2000);
    console.log("Did we make it? "+success); // here: the none of the waitFor functions are executed yet
});

对于其他步骤不在其他步骤中的全局案例,情况也是如此。你可以做的是让console.log异步。

var success = false;
casper.waitFor(check, function then(){
    casper.echo("Great success");
    success = true;
}, onTimeout, 2000);
casper.then(function(){
    // here: the waitFor functions are guaranteed to have run
    console.log("Did we make it? "+success);
});