为什么waitFor()忽略了我的返回值?

时间:2015-04-01 14:21:58

标签: javascript casperjs

此代码无效:

casper.waitFor(function check(){
    //Wait for new line to appear in the table and the input box to be emptied
    console.log("In waitFor:");
    console.log(casper.evaluate(function(){return $("table.packagesListing  tr td:contains('some text')").length;}) );
    console.log(casper.evaluate(function(){return $("table.packagesListing  tr td:contains('some text')").length;}) == 1 );
    return
      casper.evaluate(function(){return $("table.packagesListing  tr td:contains('some text')").length;}) == 1
      //&&
      //(casper.evaluate(function(){return $('input#addNewPackage').val();}) == "")
      ;
    },function then(){},
    function onTimeout(){
        this.capture("screenshots/"+label+".failed_timeout_waiting_for_package_add.png");
    });

当我运行它时,我看到的是:

In waitFor:
1
true
In waitFor:
1
true
...
In waitFor:
1
true
In waitFor:
1
true

然后我得到超时!我必须遗漏一些非常明显的东西,因为我在这个脚本的其他地方使用了casper.waitFor(),没有任何问题!

1 个答案:

答案 0 :(得分:0)

问题是一行上的return语句本身。在JavaScript中,分号是可选的(参见Automatic semicolon insertion & return statements),因此与写作相同:

return null;
casper.evaluate(/*...*/) == 1
;

当返回多个布尔值的AND时,将它们分配给本地变量更好(并且更具可读性)。所以我的代码现在看起来像:

casper.waitFor(function check(){
    //Wait for new line to appear in the table and the input box to be emptied
    var isInTable = casper.evaluate(function(){return $("table.packagesListing  tr td:contains('some text')").length;}) == 1;
    var inputIsEmptied = casper.evaluate(function(){return $('input#addNewPackage').val();}) == "";
    return isInTable && inputIsEmptied;
    },function then(){},
    function onTimeout(){ /*...*/ }
    );