0

I have some code:

getPatients() {
        const db = firebase.database();

        let patients = [];

        let refDatabase = db.ref('patient');

        let valuesDatabase = [];
        let valuesNameArray = [];
        let valuesBirthArray = [];
        let valuesAgeArray = [];
        let valuesGenderArray = [];
        let valuesCountryArray = [];
        let valuesStateArray = [];
        let valuesCityArray = [];

        refDatabase.on('value', elem => {
            valuesDatabase = elem.val();

            valuesNameArray = Object.values(valuesDatabase.name);
            valuesAgeArray = Object.values(valuesDatabase.age);
            valuesBirthArray = Object.values(valuesDatabase.birth);
            valuesGenderArray = Object.values(valuesDatabase.gender);
            valuesCountryArray = Object.values(valuesDatabase.country);
            valuesStateArray = Object.values(valuesDatabase.state);
            valuesCityArray = Object.values(valuesDatabase.city);

            for (let i = 0; i < valuesNameArray.length; i++) {
                patients = [...patients, { name: valuesNameArray[i], age: valuesAgeArray[i], birth: valuesBirthArray[i], gender: valuesGenderArray, country: valuesCountryArray[i], state: valuesStateArray[i], city: valuesCityArray[i] }];
            }

            return patients;
        });
    };

I wrote this method in my class and try to use it in other files, smth like this:

const newPatient = new PatientService();
console.log(newPatient.getPatients());

In this console.log i got undefined. I understand why it works this way: because I wrote 'return' in refDatabase function and this return apply for this. But if I'll write 'return' after 'refDatabase' I will get undefined again because console.log works faster than refDatabase. How i can fix it?

P.s. I have read documents about promise, async\await and many other pages, but cant understand how implement solution from them to my project.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
IRonny
  • 21
  • 1
  • 7
  • 2
    Please see [How do I return the response from an aynchronous call](https://stackoverflow.com/q/14220321/438992), which this duplicates. It'll be very important to wrap your head around async programming in general for any significant JS work. – Dave Newton Jun 06 '21 at 17:57
  • `...gender: valuesGenderArray, country:...` typo error – Mister Jojo Jun 06 '21 at 18:11

0 Answers0