then()
basically adds a new navigation step in a stack. A step is a javascript function which can do two different things:
- waiting for the previous step - if any - being executed
- waiting for a requested url and related page to load
Let's take a simple navigation scenario:
var casper = require('casper').create();
casper.start();
casper.then(function step1() {
this.echo('this is step one');
});
casper.then(function step2() {
this.echo('this is step two');
});
casper.thenOpen('http://google.com/', function step3() {
this.echo('this is step 3 (google.com is loaded)');
});
You can print out all the created steps within the stack like this:
require('utils').dump(casper.steps.map(function(step) {
return step.toString();
}));
That gives:
$ casperjs test-steps.js
[
"function step1() { this.echo('this is step one'); }",
"function step2() { this.echo('this is step two'); }",
"function _step() { this.open(location, settings); }",
"function step3() { this.echo('this is step 3 (google.com is loaded)'); }"
]
Notice the _step()
function which has been added automatically by CasperJS to load the url for us; when the url is loaded, the next step available in the stack — which is step3()
— is called.
When you have defined your navigation steps, run()
executes them one by one sequentially:
casper.run();
Footnote: the callback/listener stuff is an implementation of the Promise pattern.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…