My project to compare two cities weather. My problem that I can't access the objects outside the fetch function call my object.
submitBtn.addEventListener("click", function () {
  // getting user data
  resultArea.innerHTML = "";
  loadingSec.style.display = "block";
  const firstCityName = document.getElementById("firstCityName");
  const secondCityName = document.getElementById("secondCityName");
  // inilize arrays for strong city weather daya for 8 days
  const firstCitydata = new Array();
  let secondCitydata = [];
  // get request date and calulte 8 days bevore and store it in dates array
  const dates = req_dates();
  let currentReq = [new HisCityDayWeather(), new HisCityDayWeather()];
  //fetch each day wether data
  for (let i = 0; i < dates.length; i++) {
    // first city fetch function call
    getData(firstCityName.value, dates[i]).then((data) => {
      currentReq[0].name = data.location.name;
      currentReq[0].day.push(data.forecast.forecastday[0].day);
      currentReq[0].date.push(data.forecast.forecastday[0].date);
    });
    getData(secondCityName.value, dates[i]).then((data) => {
      currentReq[1].name = data.location.name;
      currentReq[1].day.push(data.forecast.forecastday[0].day);
      currentReq[1].date.push(data.forecast.forecastday[0].date);
      stor_in_array(currentReq);
    });
  }
  function stor_in_array(citydata) {
    console.log(
      `store function call first ctiy length: ${citydata[0].day.length} second ctiy length: ${citydata[1].day.length}`
    );
    if (citydata[1].day.length === 8 && citydata[0].day.length === 8) {
      console.log(`call complte`);
      loadingSec.style.display = "none";
      build_3Row_table(dates, citydata[0], citydata[1]);
    }
  }
});
This the only way my code kind of work but I have to call the function stor_in_array 8 times.
If the first fetch call didn't finish before the second one the the condition inside stor_in_array doesn't get passed.
If I tried to call the function pillow the for loop I can't access the array.
The fetch function:
async function getData(cityName, date) {
  try {
    let response = await fetch(
      `https://api.weatherapi.com/v1/history.json?key=${wKey}&q=${cityName}&dt=${date}`
    );
    let data = await response.json();
    if (response.ok) {
      return data;
    } else {
      return data["error"]["code"];
    }
  } catch (err) {
    console.log(err);
  }
}
github repo: here
project on netifly: here when trying check the network and press compare two times the second always work if you enter the names right
note: I know there a lot of work should be done. Im Validation I am still working on it.
 
    