Skip to content Skip to sidebar Skip to footer

How To Resolve/return A Foreach Function In Cloud Functions

I have the following (sample) array: pages = [ { 'name' : 'Hello', 'id' : 123 },{ 'name' : 'There', 'id' : 987 },{ 'name' : 'Great', 'id' : 555 } ]; I want to save ev

Solution 1:

You're returning out of your function before you ever send a response. If you never send a response, your HTTPS function will time out.

Instead, you should be collecting all the promises from all the updates into an array, then wait for all of them to resolve before sending the final response. Something like this:

exports.testSaveFacebookPages = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
    let userUid = req.body.uidconstPagesRef = admin.firestore().collection(`/users/${userUid}/pages/`)
    const promises = []
    pages.forEach(function(page, index){
      const promise = PagesRef.doc(`p${index}`).update(page, { merge: true })
      promises.push(promise)
    })

    Promise.all(promises)
    .then(results => {
      res.status(200).send('Pages saved successfull!')
    })
    .catch(error => {
      res.status(500).send('error')
    })
  })
})

Post a Comment for "How To Resolve/return A Foreach Function In Cloud Functions"