如何在CasperJS中完成评估步骤?

问题描述 投票:-1回答:1

假设我有这个脚本:

var me = null;

casper
    .start()
    .then(function(){
        me = this.evaluate(someFunction);
    })
    .wait(5000) //this what i doing until now
    .then(nextFunction)

casper.run()

我需要从evaluate计算me然后在nextFunction中执行me

问题是,我不知道评估结束的确切时间。为了解决这个问题,我通常会在一定时间内使用wait()。

我不喜欢这个,因为我不能尽快执行nextFunction。在jQuery中我可以使用callback / promise来摆脱这个,但是如何在casperJS上执行此操作?

我试试这个,但没有运气,

var me = null;

casper
    .start()
    .then(myEval)
    .wait(5000) //this what i doing until now
    .then(nextFunction)

casper.run()

function myEval(){
    me = this.evaluate(someFunction);
    if(me==null) this.wait(2000, myEval);
}

所以我一直在我的脚本中添加丑陋的wait()因为我学习casperjs直到现在。

更新

建议答案的结果:

var casper = require('casper').create();
var me = 'bar';

function timeoutFunction(){
    setTimeout(function(){
        return 'foo';
    },5000);
}

function loopFunction(i){
    var a = 0;
    for(i=0; i<=1000;i++){
        a=i;
    }
    return a;
}

function nextFunction(i){
    this.echo(i);
}

casper
    .start('http://casperjs.org/')
    .then(function(){
            me = this.evaluate(timeoutFunction);
            return me;
    }).then(function() {
        this.echo(me); //null instead foo or bar
        me = this.evaluate(loopFunction);
        return me
    }).then(function() {
        this.echo(me);//1000 => correct
        nextFunction(me); //undefined is not function. idk why 
    });
casper.run();
javascript jquery phantomjs casperjs
1个回答
0
投票

你可以做Promises链接,像这样:

casper
.start()
.then(function(){
    me = this.evaluate(someFunction);
    return me;
}).then(function(me) {
  // me is the resolved value of the previous then(...) block
  console.log(me);
  nextFunction(me);
  });

另一个通用的例子可以找到here

© www.soinside.com 2019 - 2024. All rights reserved.