I am aware that a loop in js will not wait for the async process and therefor, will always be at the last iteration when the async process is done.
My Question is, how to I solve this so I can make the for loop wait for each iteration of the loop?
getChildItems() {
return new Promise((resolve, reject) => {
this.lessons.levels.map((item, i) => {
item.childlevels.map((childItem, iChild) => {
((i, iChild) => {
this.horseman
.open(childItem.url)
.html()
.then((html) => {
cheerio(html).find('.list-item a').map((index, elem) => {
let lesson = cheerio(elem);
childItem.lessons.push(
{name: lesson.text(), url: lesson.attr('href')}
);
});
})
.then(() => {
const outter = i >= this.lessons.levels.length - 1;
const inner = iChild >= item.childlevels.length - 1;
if (outter && inner) {
resolve(this.lessons);
}
});
})(i, iChild);
});
});
});
}