Nested Firebase Firestore forEach promise queries

╄→гoц情女王★ 提交于 2019-12-24 00:36:53

问题


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);
    });
  } 

来源:https://stackoverflow.com/questions/47897755/nested-firebase-firestore-foreach-promise-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!