如何解析/返回Cloud Functions中的forEach函数 [英] How to resolve/return a forEach function in Cloud Functions

查看:51
本文介绍了如何解析/返回Cloud Functions中的forEach函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下(示例)数组:

I have the following (sample) array:

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

我想将此数组中的每个对象另存为Collection中的Document. 为此,我具有以下功能:

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

该函数执行后,会将页面保存到Firestore中:) 但是似乎该函数正在循环执行.记录说:

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'

我已阅读:具有Firestore错误的云功能已超过Dealine" https://firebase.google.com/docs/functions/terminate功能

但是我找不到带有forEach的任何Cloud Function示例. 任何帮助都会很棒!

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

推荐答案

在发送响应之前,您将退出函数.如果您从不发送响应,则HTTPS功能将超时.

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.

相反,您应该将所有更新的 all 个promise收集到一个数组中,然后等待所有它们解决,然后再发送最终响应.像这样:

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')
    })
  })
})

这篇关于如何解析/返回Cloud Functions中的forEach函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆