2014-09-05 44 views
1

我试图从下面的函数返回一个值,像这样。如何从扩展casperjs函数返回值?

html = casper.get_HTML(myselector); 

我得到的所有回报是“undefined”(return_html)。但是,'html'变量设置正确。全部功能正常工作。这只是问题的返回值。

你怎么做到的?

casper.get_HTML = function(myselector) { 
    var return_html; 

    casper.waitForSelector(myselector, 
     function() { 
      var html = casper.getHTML(myselector, false); 
      return_html = html;          //got the html 
     }, 
     function() {            // Do this on timeout 
      return_html = null; 
     }, 
     10000              // wait 10 secs 
    ); 

    return return_html; 
}; 

回答

1

在CasperJS所有then*和所有wait*函数是阶跃函数,其是异步的。这意味着你不能返回你的自定义函数中异步确定的东西。您必须使用回调:

casper.get_HTML = function(myselector, callback) { 
    this.waitForSelector(myselector, 
     function then() { 
      var html = this.getHTML(myselector, false); 
      callback(html); 
     }, 
     function onTimeout() { 
      callback(); 
     }, 
     10000 // wait 10 secs 
    ); 
    return this; // return this so that you can chain the calls 
}; 

casper.start(url).get_HTML("#myid", function(html){ 
    if (html) { 
     this.echo("success"); 
    } else { 
     this.echo("failed"); 
    } 
}).run(); 
+0

谢谢。作品不错! – 2014-09-06 09:34:52