In the code below, I try to return arr
with details in it, but I think it's empty, because of the request. What can I do to make this work?
module.exports = function getWeather(country) {
var arr = [];
var pageToVisit = "https://www.timeanddate.com/weather/" + country;
console.log("Visiting page " + pageToVisit);
request(pageToVisit, function(error, response, body) {
if (error) {
console.log("Error: " + error);
}
// Check status code (200 is HTTP OK)
console.log("Status code: " + response.statusCode);
if (response.statusCode === 200) {
// Parse the document body
var $ = cheerio.load(body);
console.log("Page title: " + $('title').text());
$('div.bk-focus__qlook').each(function(index) {
var title = $(this).find('div.h2').text().trim();
//var link = $(this).find('div.h1').attr('href');
console.log('title: ' + title);
//console.log(link);
arr.push(title)
});
}
});
return arr;
}
The arr
is always empty, and I can't add the title
to the arr
. How can I wait for it?