0

I'm currently trying to make a Casper module that does something using a casper module, and returns a variable from that, kinda like this:

var data = [];

exports.parsePage = function(argUrl) {

    url = baseUrl = argUrl;

    if (!url) {
        casper.warn('No url passed, aborting.').exit();
    }

    casper.start('https://js-uri.googlecode.com/svn/trunk/lib/URI.js', function() {
        var scriptCode = this.getPageContent() + '; return URI;';
        window.URI = new Function(scriptCode)();
        if (typeof window.URI === "function") {
            this.echo('URI.js loaded');
        } else {
            this.warn('Could not setup URI.js').exit();
        }
        //process is a function that processes the page
    }).run(process);

    return data;
}

and my test looks like this:

var scanner = require('./pageParser');

console.log(JSON.stringify(scanner.parsePage('http://url.com')));

Is it possible to wait for casper to finish execution before returning data in the parsePage function?

4

1 回答 1

1

您可以使用从 phantomjs 获取的这个示例中的类似等待的函数,但是您缺少 javascript 的一个基本概念:异步和回调。

所以,一个可能的解决方案是......

模块pageParser.js

function process(callback) {
    //do something here
    callback(data);
}

exports.parsePage = function(argUrl, callback) {
   ...
    casper.start('https://js-uri.googlecode.com/svn/trunk/lib/URI.js', function() {
        ...
    }).run(process(callback));
}

主脚本:

var scanner = require('./pageParser');

scanner.parsePage('http://url.com', function(data) {
console.log(JSON.stringify(data));
});
于 2013-07-25T07:49:52.187 回答