1

I want to get the orders after completing all the pushes to the PrevOrders array. I tried different techniques. when I console the result the array is printed but I can't get the size of it or even manipulate it. How can I get the result?

this.PrevOrders=[];
orderList.forEach(order=>{ 
  let orderObject= order.payload.toJSON();
  if(orderObject&&orderObject['status']=="Order Delivered"){
  let orderItems= 
    this.afdb.object(`/OrderItems/${order.key}`);
  orderItems.snapshotChanges().subscribe(items=>{
    let itemsO=items.payload.toJSON();
    let OrderProducts=[]; 
    if(itemsO){ 
      for (const key in itemsO) {
        if (itemsO.hasOwnProperty(key))
         {                
          this.afdb.database.ref(`/Items/${key}`)
          .child('type').once('value')
          .then(item=>{
            if(OrderProducts.indexOf(item.toJSON())==-1)
                OrderProducts.push(item.toJSON());
           });
         }
     }
    this.length=this.PrevOrders.push(OrderProducts);
    }
  });
 }
});
Promise.resolve(orderList).then(()=>{
  console.log(this.length);
  console.log(this.PrevOrders);
});
Zainab
  • 15
  • 6
  • 1
    [Do not use `forEach`](https://stackoverflow.com/q/37576685/1048572). You also will need to promisify `subscribe` and do something about the `itemsO` loop – Bergi Dec 01 '18 at 13:23

1 Answers1

0

You are adding the elements of the array OrderProducts in an async context, this phrase of yours is key: "after completing all the pushes to the PrevOrders array".

You are currently not waiting for all your async calls to finish. You need to collect all the promises you are generating, then wait for all of them to finish before accessing your data.

Promise.all(myArrayOfPromises).then(
 () => { /* access your data */ }
)

On top of that, you have also an additional async context coming from a subscription to an observable. Assuming that you will only get one value from that subscription, you will need to convert it into a promise and add it to the list of promises that you have to wait for.

yms
  • 10,361
  • 3
  • 38
  • 68