Yes, otherwise synchronous functions like casper.exists do not make sense.
In your example, no_error never be true because the casper.start is executed asynchronously while if (no_error) is evaluated for a long time.
You need to nest several steps (all wait* and then* functions are steps) for this:
var casper = require('casper').create(); var no_error = false; casper.start('http://casperjs.org/', function() { this.echo(this.getTitle()); no_error = true; }); casper.then(function(){ if (no_error) { casper.thenOpen('http://phantomjs.org', function() { this.echo(this.getTitle()); }); } }); casper.run();
You can nest the functions of a step, but you should keep in mind that after a step you should not use a synchronous function, because it will be executed the other way around.
casper.then(function(){ casper.thenOpen('http://phantomjs.org', function() { this.echo("1: " + this.getTitle()); }); this.echo("2: " + this.getTitle()); });
will print the first 2 and then 1.
Synchronous
If these conditions are returned synchronously, you can evaluate it directly
casper.start('http://casperjs.org/', function() { var array = this.evaluate(function(){....}); if (array && array.length > 2) { this.thenOpen(...); } });
There is simply no need for an extra step.
Asynchronous
Here it becomes interesting. If, for example, you have to run a long script in the context of the page (this is not limited to the context of the page), you will have to wait for it to complete in the context of casper. You will need an indicator variable.
casper.thenEvaluate(function(){ longRunningFunction(function callback(){ window.__someIndicator = true; }); }); casper.waitFor(function check(){ return this.evaluate(function(){ return !!window.__someIndicator; }); }, function then(){ this.thenOpen(...); }, function onTimeout(){ this.echo("failed"); this.thenOpen(...);
Sometimes you do not have a callback option. In this case, the DOM is likely to change, and you will have to wait for these changes.
Conclusion
The example in the first fragment is not very useful and should be exchanged for one of the other approaches.