How to resolve/return a forEach function in Cloud Functions

孤街浪徒 提交于 2020-01-25 23:01:28

问题


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!


回答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.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')
    })
  })
})


来源:https://stackoverflow.com/questions/47470690/how-to-resolve-return-a-foreach-function-in-cloud-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!