Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to add a .then promise to a for Loop?

I am working on a Firebase cloud function to update a field value for every element of the array I provide.

Below is my loop.

I would like for it to add a document to another collection as soon as this loop has been completed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// FOR EACH ITEM
sortedArray.forEach(([key, val]) => {
    walletRef.doc('j10wmCUhUWPxYJpIElBxmFAEI6l1').update({
        [val.product]: admin.firestore.FieldValue.increment(val.quantity),
    })
})

When I try to add a .then like below, it fails

// FOR EACH ITEM
sortedArray.forEach(([key, val]) => {
    walletRef.doc('document_id_here').update({
        [val.product]: admin.firestore.FieldValue.increment(val.quantity),
    })
}).then((doc) => {
    logsRef.add({
        user_id: "document_id_here",
        product: items,
        transactionType: "purchase",
        date: new Date(),
    })
});

Logged error:

textPayload: "Function execution took 2594 ms, finished with status: 'crash'"

The field values are updated but the new document is not created.
Please help.
Thanks.

>Solution :

Your update loop seems unnecessary since you’re performing the operations on the same document.

Try something like this instead, setting multiple properties at once

walletRef
  .doc("document_id_here")
  .update(
    Object.fromEntries(
      sortedArray.map(({ product, quantity }) => [
        product,
        admin.firestore.FieldValue.increment(quantity),
      ])
    )
  )
  .then((writeResult) => {
    // ...
  });

From the docs for Increment a numeric value

★ Note: If the field does not exist or if the current field value is not a numeric value, the operation sets the field to the given value

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading