Допустим, у меня есть этот скрипт:
var me = null;
casper
.start()
.then(function(){
me = this.evaluate(someFunction);
})
.wait(5000) //this what i doing until now
.then(nextFunction)
casper.run()
Мне нужно вычислить me
из вычисления, затем выполнить me
в следующей функции.
Проблема в том, что я не знаю точно, когда закончится оценка. Чтобы исправить это, я обычно использую wait () с определенными секундами.
Мне это не нравится, потому что я не могу выполнить nextFunction
КАК МОЖНО СКОРЕЕ. В jQuery я могу использовать callback / обещание, чтобы избавиться от этого, но как это сделать на 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);
}
Так что я продолжаю добавлять уродливый wait () в свой скрипт, так как до сих пор изучаю casperjs.
Обновление
Результат от предложенного ответа:
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();