I am trying to return a value from the below function like so.
html = casper.get_HTML(myselector);
All I am getting returned is "undefined" (return_html). However, the 'html' variable is getting set properly. The over all function works properly. It's just the return value that is the issue.
How do you do it?
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;
};
In CasperJS all then*
and all wait*
functions are step functions which are asynchronous. It means that you cannot return something that is determined asynchronously in your custom function. You have to use a callback:
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();
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加