MaineKampfCoon
MaineKampfCoon

Reputation: 11

How to use PhantomJS's webpage.open callback in function return?

I'm trying to use webpage.open method's callback inside function, but getting undefined value:

getPagesCount = function (url)
{
    var page = require('webpage').create();

    return page.open(url, function (status) {
      if (status === 'success') {
        return page.evaluate(function() {
          return document.body.innerHTML;
        });
      }
    });
}
html = getPagesCount('http://google.com');
console.log(html);
phantom.exit();

gets 'undefined'.

Upvotes: 0

Views: 1553

Answers (1)

dm03514
dm03514

Reputation: 55962

i don't think thats the way async works,

the return value happens instantaneously not when your callback returns

an easy way (but increasingly complex way) to fix things, could be to move all your logic to the last callback..

getPagesCount = function (url)
{
    var page = require('webpage').create();

    page.open(url, function (status) {
      if (status === 'success') {
        page.evaluate(function() {
          var html = document.body.innerHTML;
          // now you can do something with your html!
        });
      }
    });
}

This can obviously start to get crazy very quickly

Upvotes: 2

Related Questions