0

I set a global variable

var URL = [];

and get the data:

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] + '***************');
});

but after this function my URL[0] shows undefined.

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

The error like this:

[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'

Why ? I can't figure it out . Any ideas ? Thanks in advance.

Morton
  • 5,380
  • 18
  • 63
  • 118

1 Answers1

1

You call an async method. Therefore you need to make sure that you get the URL's value first before calling the next method which need this variable's value. Try this:

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());
  });
});
samAlvin
  • 1,648
  • 1
  • 11
  • 35