Proposal for "do while" loop in casper

31 views
Skip to first unread message

Mark Perryman

unread,
Apr 8, 2018, 5:17:11 AM4/8/18
to CasperJS
I required a do/while loop for navigating a paginated website, and have a proposal for how this could be made a generically available function.

It is implemented by initially creating an arbitrarily large number of iterations that represents the maximum (current default 100), and at each step adding
two "then" steps.  The first can perform actions such as navigation and waiting for the next page, the second can also perform some actions but MUST return a boolean to decide whether to continue the iteration.

If the condition function ever returns false, then a "thenBypassIf" step skips all remaining iterations.

Is there any interest in adding this to the core library?

// Coffeescript
doWhile = (preAction, condition, maxIter=100) ->
    for current in [0...maxIter]
        do (current) ->
            casper.then(preAction)
            casper.then(->
                return_value = condition()
                casper.log("return = " + return_value, "warning")
                casper.log("current = " + current, "warning")
                casper.thenBypassIf(! return_value, 2 * (maxIter - current - 1)))


// Compiled Javascript
doWhile = function(preAction, condition, maxIter = 100) {
  var current, j, ref, results;
  results = [];
  for (current = j = 0, ref = maxIter; (0 <= ref ? j < ref : j > ref); current = 0 <= ref ? ++j : --j) {
    results.push((function(current) {
      casper.then(preAction);
      return casper.then(function() {
        var return_value;
        return_value = condition();
        casper.log("return = " + return_value, "warning");
        casper.log("current = " + current, "warning");
        return casper.thenBypassIf(!return_value, 2 * (maxIter - current - 1));
      });
    })(current));
  }
  return results;
};

// Quick test method.
i = 0;

doWhile(function() {
  return casper.log("preAction is here", "warning");
}, function() {
  casper.log("i = " + i++, "warning");
  return i <= 10;
});

Ken Soh

unread,
Jul 26, 2018, 1:24:18 AM7/26/18
to CasperJS
[ARCHIVE] - dropping a quick note that CasperJS, similar to PhantomJS, is not actively maintained for now.
Reply all
Reply to author
Forward
0 new messages