为什么我得到第一个数组项是未定义的?

时间:2017-07-31 10:16:24

标签: javascript phantomjs casperjs

我设置了一个全局变量

var URL = [];

获取数据:

casper.then(function () {
    // I get 19 links from this code
    URL = this.evaluate(getURL);
    // I can see i get the first link
    console.log(URL[0] + '***************');
});

但在此功能之后,我的URL [0]显示未定义。

// But this URL[0] shows the error that 
casper.thenOpen("'" + URL[0] + "'", function () {
    this.echo(this.getTitle());
});

这样的错误:

[debug] [phantom] opening url: 'undefined', HTTP GET
[debug] [phantom] Navigation requested: url=file:///Users/motogod19/PhantomPractice/parse_movie/'undefined', type=Other, willNavigate=true, isMainFrame=true
[warning] [phantom] Loading resource failed with status=fail: file:///Users/motogod19/PhantomPractice/parse_movie/'undefined'

为什么?我无法弄明白。有任何想法吗 ?提前谢谢。

1 个答案:

答案 0 :(得分:1)

您调用async方法。因此,在调用需要此变量值的下一个方法之前,您需要确保先获得URL的值。试试这个:

casper.then(function () {
  // I get 19 links from this code
  URL = this.evaluate(getURL);
  // I can see i get the first link
  console.log(URL[0] + '***************');

  if (!URL[0]) {
    // should handle the condition where url list is empty
    return;
  }

  casper.thenOpen("'" + URL[0] + "'", function () {
    this.echo(this.getTitle());
  });
});