How to transfer data from "then" methods to CasperJS?

Typically, when working with CasperJS, there are several then methods. The following is an example:

 casper.then(function(){ var a = "test"; // ... }) casper.then(function(){ // how to use the variable a in the first "then" }) 

My question is: what is the general way to pass values ​​from the former then to the next then s? For the above example, how to use a in the second then ?

+7
javascript casperjs
source share
1 answer

There are many ways, but the easiest way to use global variables. If you do not want to clutter your scripts with global variables (which should not be the same problem as global variables in the browser, because you can have different libraries there), you can use IIFE to reduce the area.

 casper.start(url); (function(casper){ var a; casper.then(function(){ // set a }).then(function(){ // use a }); })(casper); casper.run(); 

Another version of the global is to add these variables to the casper object.

Probably the cleanest solution would be to enclose those blocks that need a variable. You should keep in mind that a synchronous function call cannot appear after asynchronous (these are all wait* and then* functions). The planned steps are performed after the completion of the current stamp:

 casper.start(url).then(function(){ var a; // set a somehow this.then(function(){ // use a }); }).then(function(){ // don't use a }).run(); 
+9
source share

All Articles