title: JavaScript - Wait until all array.push() are complete before returning function
body: <p>I have written a function that loops over an object and uses <code>array.push(XYZ)</code> to append the value (<code>XYZ</code>) to the array (<code>array</code>). After the loop is complete the function returns a promise. When I use <code>myFunction().then(function(response) { console.log(response[0])})</code>, I get <code>undefined</code> in the console. When I type in <code>console.log(response[0])</code> 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.</p>
  
  <p><strong>My Code</strong> <em>(I have not included the code defining <code>db</code> but it is not important as getting the info from the database is working fine.)</em></p>
  
  <pre><code>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);
  });
  </code></pre>