Nested Firebase Firestore forEach promise queries

2019-07-08 09:06发布

问题:

I am using Firebase Cloud Firestore, however, I think this may be more of a JavaScript promise issue.

I have a collection called "students" which I am querying. For each found student I want to issue another query to find "parents" related by id.

For this, I have to nest a promise / foreach query and result inside another promise / foreach query and result.

Its currently executing the entire "students" promise/loop, returning from the function, then executing each of the "parents" promise/loops afterwards.

I want it to step through one found student, then execute all parents for that student, then go onto the next student, then return from the function.

  getStudents(grade) {
    let grade_part = this.getGrade(grade);
    var dbRef = db.collection("students");
    var dbQuery = dbRef.where('bb_current_grade', '==', grade_part);
    var dbPromise = dbQuery.get();
    var allStudents = [];
    return dbPromise.then(function(querySnapshot) {
      querySnapshot.forEach(doc => {
          console.log("student");
          var studentPlusParents = doc.data();
          studentPlusParents.parents = [];
          var dbRef = db.collection("parents");
          var dbQuery = dbRef.where('student_id', '==', doc.data().id);
          var dbPromise = dbQuery.get();
          dbPromise.then(function(querySnapshot) {
            querySnapshot.forEach(parentDoc => {
              console.log("Add parent");
              studentPlusParents.parents.push(parentDoc.data());
            });
          });
          //console.log(studentPlusParents);
          allStudents.push(studentPlusParents)
      });
      //console.log(allStudents);
      return Promise.all(allStudents);
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });
  }