Seiyria
Seiyria

Reputation: 2132

Wait for CasperJS module to finish executing before returning a value?

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?

Upvotes: 0

Views: 1915

Answers (1)

Cybermaxs
Cybermaxs

Reputation: 24558

You can use a wait-like function like in this example taken from phantomjs, but you are missing a fundamental concept of javascript: async and callbacks.

So, a possible solution is...

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

main script:

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

scanner.parsePage('http://url.com', function(data) {
console.log(JSON.stringify(data));
});

Upvotes: 1

Related Questions