0

I have the following (sample) array:

pages = [ {
  "name" : "Hello",
  "id" : 123
},{
  "name" : "There",
  "id" : 987
},{
  "name" : "Great",
  "id" : 555
}  ];

I want to save every object in this array as Document in a Collection. Therefor I have the following function:

exports.testSaveFacebookPages = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
    let userUid = req.body.uid  

// pages array is available here...

    const PagesRef = admin.firestore().collection(`/users/${userUid}/pages/`)
    return pages.forEach(function(page, index){
      PagesRef.doc(`p${index}`).update(page, { merge: true })
    });

    res.status(200).send('Pages saved successfull!');
  }); // cors...
}); // exports...

When the function get executed, it saves the pages to the Firestore :) But it seems the function getting executed in a loop. The logging say:

Function execution started
Function execution took 60002 ms, finished with status: 'timeout'

I've readed: Cloud Functions with Firestore error "Dealine Exceeded" and https://firebase.google.com/docs/functions/terminate-functions

But I could not find any Cloud Function example with a forEach. Any help would be great!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Johan Walhout
  • 1,446
  • 3
  • 22
  • 38

1 Answers1

2

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.uid  

    const PagesRef = 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')
    })
  })
})
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441