0

I am writing data to firebase using a loop and async function. I am using promises to get the result of query and want to display success message when all of data is inserted. I can not figure out what I am doing wrong. I know it has a small bug. Can anyone help me?

CODE:


async function submitAttendance() {
  var uploadPromises = [];

  for (var j = 0; j < i; j++) {

    uploadPromises.push(
      new Promise((resolve, success) => {
        var naid = "name" + j + "";
        var na = document.getElementById(naid).innerHTML + "";

        var stid = "status" + j + "";
        var stat = document.getElementById(stid).value + "";

        var uidid = "uid" + j;
        var uidstu = document.getElementById(uidid).innerHTML + "";

        var attinfo = {
          student_Id: uidstu,
          student_attendanceValue: stat,
          student_class: clstd,
          student_name: na
        };
        db.collection("Parent").doc(uidstu).collection("Attendance").doc(f).set(attinfo).then(function () {
          console.log(attinfo);
        });
      })
    )

  }
  await Promise.all(uploadPromises)


  alert("Attendance Marked Successfully");

}

AZ_
  • 3,094
  • 1
  • 9
  • 19
Lucky
  • 121
  • 1
  • 3
  • 13

1 Answers1

1
uploadPromises.push(
      new Promise((resolve, success) => {
        ...
        db.collection("Parent").doc(uidstu).collection("Attendance").doc(f).set(attinfo).then(function () {
          console.log(attinfo);
          resolve();
        });
      })
    )

You need to resolve inside your promise somewhere. Presumably in the .then of your db interaction

However, rather than returning a manually created promise, you may consider pushing the db interaction itself if it is a promise, which it looks like:

for (var j = 0; j < i; j++) {

        var naid = "name" + j + "";
        var na = document.getElementById(naid).innerHTML + "";

        var stid = "status" + j + "";
        var stat = document.getElementById(stid).value + "";

        var uidid = "uid" + j;
        var uidstu = document.getElementById(uidid).innerHTML + "";

        var attinfo = {
          student_Id: uidstu,
          student_attendanceValue: stat,
          student_class: clstd,
          student_name: na
        };

    uploadPromises.push(
      db.collection("Parent").doc(uidstu).collection("Attendance").doc(f).set(attinfo).then(function () {
          console.log(attinfo);
        });

    )

  }
TKoL
  • 13,158
  • 3
  • 39
  • 73