0

I want casperjs to make an ajax call but wait for the result from my server. This might take up to 3 minutes, but I can tell from looking at the results of running my script, casper.then function times out and just keeps going after exactly 30 seconds. I've tried putting casper.options.waitTimeout = 180000 /* 3 minutes */; in my code, which does work, and I've tried using this block of code, which seems to wait 3 minutes every single time regardless of the result of my api call.

I also know that the evaluate function returns only a boolean every time no matter what, and this won't work as I need the api call data that is returned in the rest of my script. How can I get this function to wait for 3 minutes? And there is a lot going on behind the scenes, so yes, I need to wait this long.

var casper = require('casper').create();

casper.start('mysite.html', function() {
});

casper.then(function() {
  result = getSomethingFromMyServerViaAjax( theId );
});

This is the alternate method that I've tried that seems to always wait 3 minutes regardless or speed of the ajax call coming back.

casper.waitFor(function check() {
    return this.evaluate(function() {
        return result = getSomethingFromMyServerViaAjax( theId ) /* this takes up to 3 minutes */;
    });
}, function then() {
   casper.log("Doing something after the ajax call...", "info");
   this.die("Stopping here for now", "error");
}, 180000 );

I have tested my ajax call elsewhere and it works, as long as the response comes back in under 30 seconds, but if it doesn't casper just skips that block and keeps going every time.

Jeremy Gehrs
  • 413
  • 6
  • 17

1 Answers1

2

You were nearly there. You need to trigger your long running call. It seems that it is synchronous so I put it inside setTimeout. The result is written after some time into window.resultFromMyServerViaAjax.

this.evaluate is also synchronous, but after it is executed, the wait step is scheduled and tests periodically whether the window property is set.

var casper = require('casper').create(),
    theId = "#whatever";

casper.start('mysite.html');

casper.then(function() {
    // trigger 
    this.evaluate(function(theId){
        window.resultFromMyServerViaAjax = null;
        setTimeout(function(){
            window.resultFromMyServerViaAjax = getSomethingFromMyServerViaAjax(theId);
        }, 0);
    }, theId);
    this.waitFor(function check() {
        return this.evaluate(function() {
            return !!window.resultFromMyServerViaAjax;
        });
    }, function then() {
       casper.log("Doing something after the ajax call...", "info");
    }, function onTimeout() {
       this.die("Stopping here for now", "error");
    }, 180000 );
});
casper.run();
Artjom B.
  • 61,146
  • 24
  • 125
  • 222