如何在PhantomJS中循环遍历数组/对象

时间:2013-09-26 11:55:00

标签: phantomjs casperjs

我有一个想要循环的对象。目前正在循环它如下:

for(var i = 0; i< coupons.length; i++) {
   var couponObj = [];
var coupon=coupons[i];

var casper = require('casper').create();            
casper.start();




     casper.then(function(){console.log(JSON.stringify(coupon);}
    //some other work
    );

}

问题是它在没有输入casper.then(function(){console.log('here')}

的情况下立即执行循环

一旦执行了循环,它就会用最后一个值ie casper.then(function(){console.log(JSON.stringify(coupon);}执行。 coupons[coupons.length]

1 个答案:

答案 0 :(得分:1)

因为许多CasperJS的函数都是异步的,所以不将代码包装在Casper.then中会导致它们无序运行。您可以使用以下内容解决此问题。

var coupons = [[1, 2], [2, 3], [3, 4]]; // fake values for testing

casper.start();

casper.then(function() {
    this.eachThen(coupons, function(response) {
        console.log(JSON.stringify(response.data));
    });
});

casper.run();

这至少需要CasperJS 1.1-beta1才能运行。

相关问题