A commonly used method (for good reasons) for dealing with this problem is using a promise.
There are many different implementations of promises. A lot of frameworks have their own promises included, such as jQuery and AngularJS. There are also stand alone promise frameworks, such as Q
.
Promises are a way of chaining methods by resolving values. Once resolved the next function in the chain will be called.
When you'd use Q, your code could look like:
var baseTargetUrl = Q.defer();
.....
casper.then(function() {
var value;
baseTargetUrl.resolve(value = this.evaluate(function() {
return __utils__.getElementByXPath('//*[@id="wrapper"]/div[1]/a[2]')["href"];
}));
console.log('logging: ' + value); // works
});
baseTargetUrl.then(function (value) {
casper.thenOpenAndEvaluate(value, function () { // value contains the result of the call above
var test = document.querySelector('myselector');
//do other stuff
});
});
Promises are a way of dealing with async code to prevent it from becoming spaghetti, to keep things sane.
In a small situation like this, simply nesting the functions could be your solution too.
var baseTargetUrl;
.....
casper.then(function() {
baseTargetUrl = this.evaluate(function() {
return __utils__.getElementByXPath('//*[@id="wrapper"]/div[1]/a[2]')["href"];
});
console.log('logging: '+baseTargetUrl); // works
casper.thenOpenAndEvaluate(baseTargetUrl ,function() { //baseTargetUrl is no longer undefined, it's a closure now
var test = document.querySelector('myselector');
//do other stuff
});
});