I'm building a web scraper using Nodejs and I use a lot of asynchronous functions which I have written. I want to run a chain of functions using different page ids but for loop doesn't seem to work properly. I tried using counter variables too but it doesn't produce required results.. Please find my code below:
var pageInformation = [
['page1','id111'],
['page2','id222'],
['page3','id333']];
var reqCounter = 0;
for(page in pageInformation){
var pageName = pageInformation[reqCounter][0];
var pageId = pageInformation[reqCounter][1]
getPosts(pageId,function(err,idArray){
if(!err){
getMoreData(idArray, function(data,err){
if(!err){
populateDatabase(data, function(err,success){
if(!err){
reqCounter++;
console.log('Loop for ' + pageName + 'has finished');//prints out page1 three times
}
})
}
})
}
})
}
What happens is console.log() prints out page1 three times and and database gets populated with the first page data only. Any ideas on how I could run this chain of code for each of the pages in the pagesInformation array?