假设我有这个脚本:
var me = null;
casper
.start()
.then(function(){
me = this.evaluate(someFunction);
})
.wait(5000) //this what i doing until now
.then(nextFunction)
casper.run()
我需要根据评估计算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();
答案 0 :(得分:0)
您可以执行Promises链接,如下所示:
casper
.start()
.then(function(){
me = this.evaluate(someFunction);
return me;
}).then(function(me) {
// me is the resolved value of the previous then(...) block
console.log(me);
nextFunction(me);
});
可以找到另一个通用示例here。