I'm using casperJS to loop through an array. It works fine, except when I fire an event there appears to be some sort of race condition going on.
The script navigates to a URL, waits for a selector, and then fires an event when the selector is available in the DOM. The event listener for said event then does what it does.
But the problem is, within the for loop I am getting different results for the variable ad_id
. I have commented the code.
When I first grab the ad_id, it's different in each iteration (normal behavior). But calling it in the waitForSelector results in the same ad_id each time.
casper.then(function() {
log(username, 'Grabbing demographic text and submitting to server');
for(i=0; i < ads.length; i++)
{
ad = ads[i];
ad_id = ad.ad_id; // Here ad_id is different each iteration
dText = null;
url = 'https://example.com/page.php?ad_id=' + ad_id + '&page_type=20';
casper.thenOpen(url, function() {
casper.page.injectJs(fs.workingDirectory + '/js/jquery-2.1.4.min.js');
});
casper.waitForSelector('#static_templates', function() {
dText = casper.evaluate(function() {
return $('section').first().text();
});
log(ad_id); // Here, all ad_id's are the same every iteration
this.emit('demographic.recieved', ad_id, dText);
});
casper.wait(5000);
}
});
Any ideas?