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..

3
  • 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. Commented Apr 15, 2020 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 Commented Apr 15, 2020 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. Commented Apr 15, 2020 at 20:29

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.