2013-09-01 100 views
0

我試圖使用webpage.open內部函數法的回調,但得到未定義的值:如何在函數返回中使用PhantomJS的webpage.open回調?

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(); 

得到「未定義」。

回答

2

我不認爲多數民衆贊成的方式異步工作,

返回值瞬間發生時不回調返回

一個簡單的方法(但日益複雜的方式)來解決的事情,可能是移動所有的邏輯,最後回調..

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

+0

dm03514,有唯一的辦法?我不能在getPagesCount基金之外使用var html嗎? – MaineKampfCoon