The request()
module is asynchronous, so console.log()
is executing before the HTTP call completes when you use console.log()
. For example, take this code:
var request = require('request');
var cheerio = require('cheerio');
var url = 'http://www.primarytalent.com/';
var artistURLs = [];
request(url, function(err, resp, body){
if (err)
throw err;
$ = cheerio.load(body);
$('#rosterlists div li a').each(function(){
var urlCap = this.attr('href').slice(1);
var artistURL = url.concat(urlCap);
artistURLs.push(artistURL);
console.log('push');
});
});
console.log(artistURLs);
You will see this result:
[]
push
push
...
push
push
push
To prevent this from happening, only use the variable artistURLs
inside of the HTTP request callback.