我正在尝试从下面的函数返回一个值,如下所示。
html = casper.get_HTML(myselector);
我得到的只是“未定义”(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;
};
最佳答案
在 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();
关于javascript - 如何从扩展的 casperjs 函数返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25695079/