Lately I'm messing around with promises. What I am trying to achieve in the extractMovie()
is to loop through all the given urls, parse them, get some date, store it in an array and to resolve that array. But what actually happens is resolving the result
(which is an empty array) and then looping through the urls. So actually an empty array is being resolved to the parallel()
function. Any ideas on how to achieve that synchronicity in the promise?
const extractMovie = (movieUrl) => {
return new Promise((resolve, reject) => {
const fullUrl = mainDomain + movieUrl;
domParser(fullUrl).then(($) => {
const titleSelector = '.title h2';
const ratingSelector = '.user_score_chart';
const runtimeSelector = '.facts p:nth-child(9)';
const obj = {
title: $(titleSelector).html(),
rating: $(ratingSelector).attr('data-percent'),
runtime: $(runtimeSelector).text(),
};
resolve(obj);
});
});
};
const arrayProcessing = async (array) => {
const results = [];
for (const entry of array) {
results.push(await extractMovie(entry));
}
return results;
};
const parallel = async (movieUrl1, movieUrl2) => {
const task1 = arrayProcessing(movieUrl1);
const task2 = arrayProcessing(movieUrl2);
return {
res1: await task1,
res2: await task2,
};
};
const run = async () => {
try {
const urls = await goInPage();
await parallel(urls.page1, urls.page2).then((result) => {
console.log(result);
});
} catch (err) {
console.log(err);
}
};
run();