如何从扩展的casperjs函数返回值

How to return value from an extended casperjs function?

本文关键字:casperjs 函数 返回值 扩展      更新时间:2023-09-26

我正试图从下面的函数中返回一个值,如下所示。

html = casper.get_HTML(myselector);

返回的只是"undefined"(return_html)。但是,"html"变量的设置是正确的。over-all函数工作正常。这只是回报值的问题。

你是怎么做到的?

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;
 };

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