【问题标题】:How to wait until evaluate step done in CasperJS?如何等到在 CasperJS 中完成评估步骤?
【发布时间】:2018-08-30 19:23:28
【问题描述】:

假设我有这个脚本:

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 中我可以使用回调/承诺来摆脱这个,但是如何在 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);
}

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

更新

建议答案的结果:

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();

【问题讨论】:

  • 您可以在设置me 值后在then 函数内调用nextFunction。这对你有用吗?
  • @LuizCarlos 那行不通。我试了几次。顺便说一句,您能给我示例代码吗,您无需尝试,我会为您尝试。因为也许我只是误解了你的意思
  • 有用的反馈:我对这篇文章中缺少拼写和大小写的问题投了反对票。请使用英语的普通大小写规则,并在发布之前对所有内容进行拼写检查。
  • (奇怪的错误当然可以,但出于“审美”原因故意弄错就不行了。)
  • 我赞成 cz 你给出原因。这很有帮助。

标签: javascript jquery phantomjs casperjs


【解决方案1】:

你可以像这样进行 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。

【讨论】:

  • 第二个函数中的我成为 casper 对象:{"contentType":"text/html; charset=utf-8","headers":[{"name":"Server","value":"GitHub.com"}, too long to post here
  • casperjs中的js类似,但根据浏览器中的js不同
  • 您能否详细说明您要实现的目标?无论您使用什么框架/库,JavaScript 承诺的工作方式都是相同的。您无需通过设置超时来等待。如果您将这些 Promise 链接起来,您将在计算出第一个区块后立即获得结果。
猜你喜欢
  • 2013-02-05
  • 1970-01-01
  • 2018-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多