When i console.log the output from getSpecificMonitorNews(url); i get the actual results. But when i use return await getSpecificMonitorNews(url);, the first results are overwritten by the last result received.
let newsContents = {
title: "",
imageSrc: "",
contents: "",
date: "",
};
async function getSpecificMonitorNews(url) {
let monitorBaseUrl = "https://www.monitor.co.ug";
url = monitorBaseUrl + url;
console.log(url)
const data = await fetchPage(url);
let $ = cheerio.load(data);
newsContents.title = $(".title-medium").text();
newsContents.imageSrc = monitorBaseUrl + $(".lazy-img-container img").attr("src");
newsContents.contents = $(".paragraph-wrapper > p").text();
newsContents.date = $("time").text();
return newsContents;
}
async function getMonitorNews(urlNews) {
return await Promise.all(
urlNews.map(async (url) => {
return await getSpecificMonitorNews(url);
})
);
}
newsContents is a global variable so its value changes. You're returning a reference to that global object, not a copied version (and there's no need to copy it if you just bring it inside the function).
So you can either move newsContents inside the function if you don't need it elsewhere:
async function getSpecificMonitorNews(url) {
let newsContents = {
title: "",
imageSrc: "",
contents: "",
date: "",
};
// rest of code
}
// rest of code
Or make a copy of the newsContents variable
// rest of code
async function getSpecificMonitorNews(url) {
// rest of code
return { ...newsContents };
}
// rest of code
Or just create a new object on the fly:
async function getSpecificMonitorNews(url) {
// rest of code
return {
title: $(".title-medium").text(),
imageSrc: monitorBaseUrl + $(".lazy-img-container img").attr("src"),
contents: $(".paragraph-wrapper > p").text(),
date: $("time").text(),
};
}
// rest of code