When I run the following searchSessionData
function, the log statements gets printed in the following order - 1,3,4,5,2 instead of 1,2,3,4,5.
Overview:
searchSessionData
basically finds unseen dates range and then using that range it calls the fetchData
function and then it just prints in the console.
fetchData
uses the dates and fetches data and pushes all of them to a dataMap => it is a map
and returns the data back
async function searchSessionData(sdate,edate){
var data;
// get range
var unseenDates=getUnseenDates(new Date(sdate),new Date(edate));
unseenDates.forEach( range => {
fetchData(range.start,range.end);
});
// weave all data
console.log(3);
data=[];
var allDatesinrange= getAllDates(new Date(sdate), new Date(edate));
console.log(4);
printElements(allDatesinrange);
console.log(5);
}
// fetch data from the API and stores it to the hashmap
const fetchData = async(sdate='', edate='')=>{
try {
// console.log('fetching...')
var response;
var data;
// send requests to fetch data from api
console.log(1);
response = await fetch(`${APOD_url}${api_key}${startDate}${sdate}${endDate}${edate}`)
currentDataIndex=0;
data = await response.json();
//if data is array, enter data to map for each entry
// console.log(dataMap);
data.forEach(async element => {
await dataMap.set(element.date),element);
});
console.log(2);
return data;
} catch (error) {
console.log(error)
return
}
}
Anyone know what the issue is and how can it be solved? I am not quite sure but I think it could be due to the promises.