0

So I'm trying to update items balance whenever a new sale is created so I am listening on that sale create and getting all items to check for matching id between new sale and items and update its balance

function is deployed but nothing changes in items balance

 export const itemsBalance = functions.firestore

.document("sales/{id}")
.onCreate((snap, context) => {
  //get sale data and items data
  const data = snap.data();

  //get all items
  let myItems;
  firebase.firestore().collection('items').get()
  .then(snapshot => {
      myItems = snapshot.docs.map(doc => doc.data());

      data.items.forEach((element, index) => {
          let updatedItem = myItems.find(el => el.id == element.id);
          if(updatedItem) {
              updatedItem.balance = updatedItem.balance - element.qty;
          }



          firebase.firestore().collection(`items/${element.id}`)
          .doc().update(updatedItem)
          .then(res => console.log(res))
          .catch(err => console.log(err));
          })
        })
        .catch(err => {
          console.log(err)
        })
      return data;
   });

package.json

  "dependencies": {
    "firebase-admin": "^7.3.0",
    "firebase-functions": "^2.3.0"
   }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Omar Abdelhady
  • 1,528
  • 4
  • 19
  • 31

1 Answers1

0

You're not returning a promise that resolves when all the async work is completely done. You need to take all the promises returned from update(), push them into an array, and use Promise.all() on that array to generate a new promise that will resolve after all the work is complete. Return that promise from the function.

See also:

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441