0

i have some trouble. I want my function execute when my array is complete. But the my function execute although my array is not complete. can you fix my code please..

const historyPermintaanObat2 = obat => {
let array = [];
db.child("itemPermintaan")
  .orderByChild("id")
  .equalTo(obat.id)
  .on("child_added", snapshot => {
    let obj = snapshot.val();
    let registerPermintaanRef = db.child(
      `registerPermintaan/${obj.idPermintaan}`
    );
    registerPermintaanRef.once("value", snap => {
      let username = snap.val().username;
      let createdAt = snap.val().createdAt;
      let approvedAt = snap.val().approvedAt;
      let unit = snap.val().unit;
      let obj2 = { ...obj, username, createdAt, approvedAt, unit };
      array.push(obj2);

    });
  });
return array;
};

The result is [] empty array. If i change the return array.length > 0 && array nothing is happen..

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Moh Jonaidy
  • 75
  • 1
  • 10
  • In your first query, you should use `once()` instead of `on()`, so you can get a promise that resolves when the query is complete. Use these promises (chaining both calls to `once()`) to return another promise that the caller can use the get the desired value. – Doug Stevenson Apr 15 '20 at 20:05
  • you should mention their username with @ symbol if you want them to be notified when you comment dear moh jonaidy; like this @DougStevenson – Mechanic Apr 15 '20 at 20:28
  • @DougStevenson i had tried your suggestion, but the result is empty array [ ]. The problem is, if i execute my function twice, then it will get some array. i want my function execute once, await until the array complete then outcome the result. – Moh Jonaidy Apr 15 '20 at 20:29

1 Answers1

1

I have figured it out, use once and Promise.all()

const historyPermintaanObat2 = obat => {
db.child("itemPermintaan")
  .orderByChild("id")
  .equalTo(obat.id)
  .once("value", snapshot => {
    let array = [];
    let obj = Object.values(snapshot.val());
    obj.forEach(e => {
      let registerPermintaanRef = db.child(
        `registerPermintaan/${e.idPermintaan}`
      );
      let promise = registerPermintaanRef.once("value").then(snap => {
        let username = snap.val().username;
        let createdAt = snap.val().createdAt;
        let approvedAt = snap.val().approvedAt;
        let unit = snap.val().unit;
        let obj2 = { ...e, username, createdAt, approvedAt, unit };
        return obj2;
      });
      array.push(promise);
    });
    return Promise.all(array).then(value => {
      return value;
    });
  });
 };

Here's the reference i've got Promise.all with Firebase DataSnapshot.forEach

Moh Jonaidy
  • 75
  • 1
  • 10