0

I'm trying to get the total amount for every object.amount under a category in firebase.

/* Returns a Firebase list object as an array */
  getListAsArray(path: string): Array<any> {
    let arr = new Array<any>();
    this.af.database.list(path).$ref.on("child_added", childs => { 
      childs.ref.orderByChild
      childs.ref.once("value", obj => {
        let object = obj.val();
        object.$key = obj.key;
        arr.push(object);
      });
    });
    return arr;                                                       //Works fine
  }

  //Returns the total sum for each object.amount under a category
  getTotalAmount(path: string){
    let category: any[] = this.fbp.getListAsArray(path);
    let totalAmount: number = 0;

    category.forEach( category => {
      totalAmount += category.amount;
      console.log(totalAmount);                                    //Does not print
      console.log("test");                                         //Does not print
    });

    console.log(category);              //Printes the array with every object as expected.
    return totalAmount;                 //Always returns 0
  }


/* In a constructor */
let totalAmountFood = cp.getTotalAmount('/expense/food');
console.log(totalAmountFood);                                       //Prints "0"
  1. Getting the list object from firebase returns the expected value
  2. The category.forEach() loop does not seem to get executed.
Kevin Frostad
  • 181
  • 1
  • 1
  • 12
  • 1
    *"//Printes the array with every object as expected."* That's because by the time you can look at the console, the array has finally been populated. This is another *"why is my variable unaltered / async"* question. –  Nov 26 '16 at 16:37
  • I know that. But why isn't the for loop executing? – Kevin Frostad Nov 26 '16 at 16:40
  • 1
    Because the array is empty. Read [this](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) and [this](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –  Nov 26 '16 at 16:41
  • Then which method should I use to wait for 'category' to be populated? – Kevin Frostad Nov 26 '16 at 16:48
  • 1
    There are different ways to solve the problem but they all come down to basically waiting for the response *without* pausing your script at the point where you need the response. There are many resources on *asynchronous* programming in JS/Node, so I'd recommend taking a little time to research the topic. It's not difficult but it does require that one thinks about the problem a little differently. –  Nov 26 '16 at 17:03
  • Will do. Thank you :) – Kevin Frostad Nov 26 '16 at 17:19
  • You're welcome. Good luck! –  Nov 26 '16 at 17:57

0 Answers0