I was trying to get a few infos into a variable by scraping and collecting with the request module. My guess is that I am unable to show the results in the temp_table
variable because it is not executed in the correct timing, as the request method is asynchronous while console.log(temp_table)
is not.
I thought about adding a callback to my code but I have no idea where to add it, giving the codebase below.
My interest is in populating the array temp_table
with what comes out of the request function which is run as many times as the length of the places
array.
----------------------------------------------
var request = require("request"),
cheerio = require("cheerio"),
fs = require("fs");
var places = [
{
'url' : 'http://www.ilmeteo.it/portale/meteo/previsioni.php?citta=Empoli&c=2635&gm=10&g=1&lang=ita',
'city' : 'a town'}
{
'url' : 'http://www.ilmeteo.it/portale/meteo/previsioni.php?citta=Roma&c=2635&gm=10&g=1&lang=ita',
'city' : 'another town'}
{
'url' : 'http://www.ilmeteo.it/portale/meteo/previsioni.php?citta=Firenze&c=2635&gm=10&g=1&lang=ita',
'city' : 'another town'}
];
var temp_table = [];
luoghi.forEach(function(el){
request(el.url, function (error, response, body) {
if (!error) {
var $ = cheerio.load(body);
temp = $(".datatable .expa").html();
var h = [], t = [], u = [];
// temp contains the data from the website in html format, it is rewritten in each iteration
var orario = $(".datatable .expa .ora").text().trim();
orario = orario.match(/.{1,2}/g);
for (i = 0; i < 3; i++){
h.push(orario[i]);
}
var temperatura = $(".datatable .expa .col4 span").text().trim();
temperatura = temperatura.match(/\d+\.\d+/g);
ascii_code_temperatura = String.fromCharCode(176);
for (i = 0; i < 3; i++){
t.push(temperatura[i] + ascii_code_temperatura);
}
var humidity = $(".datatable .expa .col10 span:first-child").text().trim();
humidity = humidity.match(/\d+\%/g);
for (i = 0; i < 3; i++){
u.push(humidity[i]);
}
temp_table.push({
"city" : el.city,
"t1" : {
"ora" : h[0],
"temperatura" : t[0],
"humidity" : u[0]
},
"t2" : {
"ora" : h[1],
"temperatura" : t[1],
"humidity" : u[1]
},
"t3" : {
"ora" : h[2],
"temperatura" : t[2],
"humidity" : u[2]
}
});
} else {
console.log("We’ve encountered an error: " + error);
}
//temp_table is readable here
});
//temp_table is empty here, probably because of callback
console.log(temp_table)
// THIS ONE UP HERE IS NOT READ, IT LOGS AN EMPTY ARRAY EACH TIME
}); // FOREACH END
console.log(temp_table)
// THIS ONE UP HERE IS NOT READ, IT LOGS NOTHING
Thanks in advance for the help.
Edit: marking it as a duplicate without actually helping me is not helpful at all. I did search for answers before posting the question and I didn't come up with one, hence the question.