I have a function that uses the module cherio to get data from a website.
Now I'd like to iterate this function over an array of keywords, collect the intermediate results in an array named stats and finally print the results of the stats array to the console via console.log()
Whenever I run this script it triggers the async function quickly and prints an empty stats array.
Now my question: How can I wait for the async functions to complete so that I can print the array to console when it's populated / finished.
I have googled a lot and searched stack overflow. There seem to be many ways to accomplish my goal, but what is the most idiomatic way in node to do this?
Here is the way I solved it:
var request = require("request"),
cheerio = require("cheerio"),
base_url = "http://de.indeed.com/Jobs?q="; // after equal sign for instance: sinatra&l=
/* search syntax:
- http://de.indeed.com/Jobs?q=node&l=berlin&radius=100
-
-
*/
// //
var search_words = ["django", "python", "flask",
"rails", "ruby",
"node", "javascript", "angularjs", "react",
"java", "grails", "groovy",
"php", "symfony", "laravel"
];
var counter = 0;
var stats = [];
function getStats(keyword) {
url = base_url + keyword + "&l=";
request(url, function(err, resp, body) {
if(!err) {
$ = cheerio.load(body);
data = $("#searchCount")[0].children[0].data.split(" ").reverse()[0];
stats.push([keyword, data]);
counter++;
}
// list complete?
if (counter === search_words.length) {
console.log(stats);
}
});
}
for (var j=0; j<= search_words.length; j++) {
getStats(search_words[j]);
}