I am trying to return Array of Objects from mySQL database but the array length is returning zero (no items).
I am trying to read from sample MySQL World database tables country and cities. Eventually i will create Realm document in which Country document will hold all its cities.
I am not an expert in asyn/await javascript and struggling in this. Any help would be greatly appreciated.
async function **createFile**() {
listCountry = await fetchData();
console.log(listCountry.length);
// createDocuments(listCountry);
}
async function **fetchData**() {
const countryList = new Array();
const connection = await mySQLConn;
const rsCountry = await connection.query('select * from country');
// fetch country and their cities
rsCountry.forEach(async country => {
console.log('Working on ' + country.Code);
const rsCity = await connection.query(
"select ID, Name from city where CountryCode='" + country.Code + "'"
);
// get the cities
var cityList = new Array();
rsCity.forEach(city => {
// console.log(city);
cityelem = { id: city.ID, name: city.Name };
cityList.push(cityelem);
});
// push item to array
countryList.push({
code: country.Code,
name: country.Name,
cities: cityList
});
});
return new Promise(resolve => {
console.log(countryList.length);
resolve(countryList);
});
}