Skip to content Skip to sidebar Skip to footer

Casperjs/phantomjs .then In Do/while Loop Doesn't Work

Something like this seemed pretty logical to me but caused phantom to wtfcrash (That's what it's called in the log but doesn't give helpful info)... do { casper.then(function()

Solution 1:

There are different possibilies, if you just want to repeat things static times you can use casper.repeat() -> how to have a variable value for casper.repeat

If you want to do a while with multipe then's inside and a break point you still have to use a recursive function as far as i know. Here is an example:

  ...
  casper.then(function() {
    loopValidConf.call(this, 0, 15);
  });
  casper.then(function() {
    casper.test.assert(exists, 'true after 15 tries!')
  });

  functionloopValidConf(index, numTimes) {
    if (exists === true || index >= numTimes) {
      return;
    }
    casper.then(function() {
      casper.reload(function() {
        casper.echo("reset values");
      });
      casper.then(function() {
        // set some values here
      });
      casper.then(function() {
        casper.waitForSelector(".selector")
      });
      casper.then(function() {
        if (casper.exists('.targetSelector')) {
          exists = true;
          casper.echo('targetSelector exists!');
        } else {
          casper.echo('targetSelector doesnt exists, try it once more!');
        }
      });
    });
    casper.then(function() {
      loopValidConf.call(this, index + 1, numTimes);
    });
  }
  ...

This is still not the optimum (could cause memory problems), but it works. :)

Post a Comment for "Casperjs/phantomjs .then In Do/while Loop Doesn't Work"