I'm attempting to run an automated job with CasperJS which brings in a JSON file and checks if certain elements on a given page declared in each JSON object exist. I am attempting to write this recursively, but I am running in to an issue where the beginning of the asynchronous recursive flow (i.e. my only synchronous function) is returning synchronously (as expected) and causing the script to fail.
According to this CasperJS github issue, Promises are not currently supported in PhantomJS. I have also tried the .waitFor()
CasperJS method, but this causes an infinite loop if I try and bubble up a return value of true
from the final asynchronous method (there is also the issue of waitFor being controlled by a timeout value and not waiting on a response, but the timeout value can be changed). Here is a code example attempting to use waitFor
below, simplified slightly:
casper.start(urlStart, function() {
recursiveRun(jsonInput.length);
});
var recursiveRun = function(count) {
if (count) {
casper.waitFor(function check() {
return controller(); // Infinite loop here
}, function then() {
jsonInput.shift();
recursiveRun(count - 1);
}
}
}
var controller = function() {
casper.thenOpen(jsonInput[0].url, function() {
return renavigation();
}
}
var renavigation = function() {
casper.waitForSelector("#nav", function() {
this.thenOpen(inventoryUrl, function() {
return inventoryEvaluation();
}
}
}
var inventoryEvaluation = function() {
casper.waitForSelector("#status", function() {
this.evaluate(function() {
// Unimportant in-browser function
}
return true;
}
}
casper.run();
Why is this not working? What is the proper way to recursively and asynchronously perform these actions, if at all?