此代码不起作用:
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() ,没有任何问题!
最佳答案
问题在于 return
语句本身在一行上。在 JavaScript 中,分号是可选的(参见 Automatic semicolon insertion & return statements ),因此这与编写相同:
return null;
casper.evaluate(/*...*/) == 1
;
当返回多个 bool 值的 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(){ /*...*/ }
);
关于javascript - 为什么 waitFor() 忽略我的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29393329/