I have written a function that loops over an object and uses array.push(XYZ) to append the value (XYZ) to the array (array). After the loop is complete the function returns a promise. When I use myFunction().then(function(response) { console.log(response[0])}), I get undefined in the console. When I type in console.log(response[0]) in the console, I get the correct value. What am I doing wrong? I think that it is taking time to push the value into the array but I am not 100%. Any help will be appreciated.
My Code (I have not included the code defining db but it is not important as getting the info from the database is working fine.)
function getChild(uid) {
promise = db.collection("users").doc(uid).get().then(function(doc) {
output = [];
val = doc.data();
studentsObj = val.students;
studentsObj.forEach(function(student) {
db.collection("students").doc(student).get().then(function(res) {
varl = res.data()
output.push(varl);
});
});
return output;
});
return promise;
};
getChild("parentUserID").then(function(reply) {
got = reply;
console.log(got);
});