Firebase云功能不能执行全部功能吗?

阿基尔·德米尔(Akil Demir)

我有一个Firebase Cloud函数,该函数运行并检查Firestore数据库中的对象并执行一些操作。但是它不会运行整个函数,而是会随机停止在函数中间。我首先认为它超时,但是超时值为60秒,我的函数在2-3秒内运行。但是大多数操作都需要承诺,因为它们正在执行异步操作,例如数据库操作。因此,为了确保函数在执行所有函数之前不会停止,我将它们推入promises数组并返回Promise.all(promises)。这是我的功能的样子

export const func = functions.pubsub.schedule('every 10 minutes').onRun(context => {
   const promises = any[] = [];
   //here I pass the array to some other function to gather the promises that are 
   //made there
   doSomeJob(promises)

   admin.firestore().collection('someCollection').get().then(res => {
        res.forEach(item => {
            let data = item.data();

            promises.push(somePromise);
            console.log('some Promise is pushed')
            promises.push(anotherPromise)
            .....
        })
   })

   return Promise.all(promises);
})

因此,在上面的代码中,有些承诺会得到执行,而有些则不会。不知道是什么原因。没有一个诺言会引发错误。但是原因可能是它们甚至没有被推送到数组,因为我有时看不到console.log在日志部分中运行。有时它运行有时不运行。无法弄清楚为什么它会停在中间。

我开始提出我的设计问题了。也许我应该为我应执行的每个诺言提供另一个功能。或者我有一个例如在更新对象时运行的功能。它应该做一堆事情。我的意思是一堆读写。一堆承诺。那么,为每个操作设置另一个onUpdate函数还是将其全部放入一个onUpdate函数中更好?需要帮助。提前致谢。

弗兰克·范普菲伦

如果在代码中添加一些日志记录,则很容易看到发生了什么:

export const func = functions.pubsub.schedule('every 10 minutes').onRun(context => {
   const promises = any[] = [];
   //here I pass the array to some other function to gather the promises that are 
   //made there
   doSomeJob(promises)

   console.log('Before starting to read data...');
   admin.firestore().collection('someCollection').get().then(res => {
       console.log('Got data...');
   })
   console.log('After starting to read data...');

   return Promise.all(promises);
})

当您像这样运行代码时,它记录:

在开始读取数据之前...

开始读取数据后...

得到了数据...

因此,当您return Promise.all(...)尚未从Firestore获取数据时,也没有任何等待的保证。因此,Cloud Functions可以随时终止运行您的代码的容器。

因此,解决方案是在退还所有诺言之前确保所有诺言均已收集。您可以通过Promise.all(...)在回调中放入内部回调,然后使用另一个回调return使promise兑现,以便将其返回给Cloud Functions。

export const func = functions.pubsub.schedule('every 10 minutes').onRun(context => {
   const promises = any[] = [];
   //here I pass the array to some other function to gather the promises that are 
   //made there
   doSomeJob(promises)

   return admin.firestore().collection('someCollection').get().then(res => {
        res.forEach(item => {
            let data = item.data();

            promises.push(somePromise);
            console.log('some Promise is pushed')
            promises.push(anotherPromise)
            .....
        })
        return Promise.all(promises);
   })

})

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章