【发布时间】:2018-08-30 19:23:28
【问题描述】:
假设我有这个脚本:
var me = null;
casper
.start()
.then(function(){
me = this.evaluate(someFunction);
})
.wait(5000) //this what i doing until now
.then(nextFunction)
casper.run()
我需要从 evaluate 计算 me 然后在 nextFunction 中执行 me。
问题是,我不知道评估何时结束。为了解决这个问题,我通常会在特定秒数内使用 wait()。
我不喜欢这样,因为我无法尽快执行nextFunction。在 jQuery 中我可以使用回调/承诺来摆脱这个,但是如何在 casperJS 上做到这一点?
我尝试了这个,但没有运气,
var me = null;
casper
.start()
.then(myEval)
.wait(5000) //this what i doing until now
.then(nextFunction)
casper.run()
function myEval(){
me = this.evaluate(someFunction);
if(me==null) this.wait(2000, myEval);
}
所以自从我学习 casperjs 到现在,我一直在我的脚本中添加丑陋的 wait()。
更新
建议答案的结果:
var casper = require('casper').create();
var me = 'bar';
function timeoutFunction(){
setTimeout(function(){
return 'foo';
},5000);
}
function loopFunction(i){
var a = 0;
for(i=0; i<=1000;i++){
a=i;
}
return a;
}
function nextFunction(i){
this.echo(i);
}
casper
.start('http://casperjs.org/')
.then(function(){
me = this.evaluate(timeoutFunction);
return me;
}).then(function() {
this.echo(me); //null instead foo or bar
me = this.evaluate(loopFunction);
return me
}).then(function() {
this.echo(me);//1000 => correct
nextFunction(me); //undefined is not function. idk why
});
casper.run();
【问题讨论】:
-
您可以在设置
me值后在then函数内调用nextFunction。这对你有用吗? -
@LuizCarlos 那行不通。我试了几次。顺便说一句,您能给我示例代码吗,您无需尝试,我会为您尝试。因为也许我只是误解了你的意思
-
有用的反馈:我对这篇文章中缺少拼写和大小写的问题投了反对票。请使用英语的普通大小写规则,并在发布之前对所有内容进行拼写检查。
-
(奇怪的错误当然可以,但出于“审美”原因故意弄错就不行了。)
-
我赞成 cz 你给出原因。这很有帮助。
标签: javascript jquery phantomjs casperjs