Search code examples
javascriptjqueryphantomjscasperjs

How to wait until evaluate step done in CasperJS?


Let's say I have this script:

var me = null;

casper
    .start()
    .then(function(){
        me = this.evaluate(someFunction);
    })
    .wait(5000) //this what i doing until now
    .then(nextFunction)

casper.run()

I need calculate me from evaluate then execute me in nextFunction.

The problem is, I don't know exactly when the evaluate finish. To fix this I usually use wait() with certain seconds.

I don't like this, because I can't execute nextFunction ASAP. In jQuery I can use callback/promise to get rid of this, but how to do this on casperJS?

I try this, but got no luck,

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);
}

So I keep adding ugly wait() in my script since I learn casperjs until now.

Update

Result from suggested answer:

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();

Solution

  • You can do Promises chaining, like this:

    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);
      });
    

    Another generic example can be found here.