1

我有一个代码如下

var casper = require('casper').create();
casper.on('remote.message', function (msg) {
    this.echo(msg);
});



casper.start( << some url >> , function () {
    this.echo(this.getTitle());


});
var resultObj = [];
casper.thenClick("#AddToCart").then(function () {
    // scrape something else

    casper.options.waitTimeout = 100000;

    var objectOne = this.evaluate(someFunction, << variables >> );
    //above function returns object
    casper.each(objectOne, function (self, obj) {



        var anotherObject = this.evaluate(anotherFunction, << variables >> );

        self.waitFor(function check() {

            var result = this.evaluate(thirdFunction, obj);
            if (result != 'no') {
                resultObj.push(result);


            }

            //  result = 'yes';
            return result != 'no';
            this.evaluate(function () {});
        }, function then() {


            console.log('done')


        });


    });
});

casper.run(function () {
    this.exit();
});

它包含一个循环(.each),然后是等待。我面临的问题是循环被完全执行,然后 waitFor 被执行。我怎样才能使它们同步?

4

1 回答 1

4

看起来你会想要使用casper.eachThen()而不是casper.each().

警告:您至少需要 CasperJS 1.1-beta1 才能运行它。

我无法从您的代码中获得很多东西,但看起来您可能还想将其中的一些更改casper.evaluate()casper.thenEvaluate()

我添加// ---了我在下面修改的代码。希望能帮助到你。

var casper = require('casper').create();
casper.on('remote.message', function (msg) {
    this.echo(msg);
});

casper.start( << some url >> , function () {
    this.echo(this.getTitle());
});
var resultObj = [];
casper.thenClick("#AddToCart").then(function () {
    // scrape something else

    casper.options.waitTimeout = 100000;

    var objectOne = this.evaluate(someFunction, << variables >> );
    //above function returns object

    // ---
    casper.eachThen(objectOne, function (response) {
    // ---

        var anotherObject = this.evaluate(anotherFunction, << variables >> );

        this.waitFor(function check() {
            // ---
            var result = this.evaluate(thirdFunction, response.data);
            // ---

            if (result != 'no') {
                resultObj.push(result);
            }

            //  result = 'yes';
            return result != 'no';
            this.evaluate(function () {});
        }, function then() {
            console.log('done')
        });


    });
});

casper.run(function () {
    this.exit();
});
于 2013-08-18T15:49:25.120 回答