返回值在Firebase Cloud函数中是否重要



我正在用TypeScript编写Firebase Can函数,下面是一个更新文档的简单方法。

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);
export const handleTestData = functions.firestore.document('test/{docID}').onCreate(async (snap, context) => {
const data = snap.data();
if (data) {
try {
await admin.firestore().doc('test1/' + context.params.docID + '/').update({duplicate : true});
} catch (error) {}
}
});

在这种方法中,promise由asyncawait处理,不存在return语句,并且工作良好。我看到的大多数示例/教程在每个方法中都有一个return语句。我在Firebase Cloud函数中不返回任何内容有什么影响/区别吗?如果我应该退货,我可以退货null吗?

返回值在Firebase Cloud函数中重要吗?

是的,它确实是,在云函数中,它执行异步处理(也称为"后台函数"(,以在所有异步处理完成时返回JavaScript承诺,如文档中所述。

这样做很重要,主要有两个原因(文件摘录(:

  1. 在函数成功达到终止条件或状态之前,请确保运行云函数的云函数实例不会关闭
  2. 您可以避免运行时间过长或循环无限的云函数产生过多的费用

为什么即使您没有返回Promise,您的云功能仍能正常运行

通常,您的云功能应该在异步操作完成之前终止,因为您不会返回Promise,因此会向云功能平台指示它可以终止运行云功能的云功能实例。

但有时,云功能平台不会立即终止功能,异步操作也可以完成。这根本不能保证,也完全不受你的控制。

经验表明,对于短期异步操作,最后一种情况经常发生,开发人员认为一切都很好。但是,突然之间,有一天,云功能不起作用。。。有时它确实起作用:开发人员面临着";"不稳定";行为没有任何明确的逻辑,使事情很难调试。您会在Stack Overflow中发现很多问题来说明这种情况。


具体来说,在您的情况下,您可以调整您的代码,如:

export const handleTestData = functions.firestore.document('test/{docID}').onCreate(async (snap, context) => {
const data = snap.data();
if (data) {
try {   
// See the return below: we return the Promise returned by update()
return admin.firestore().doc('test1/' + context.params.docID + '/').update({duplicate : true});
} catch (error) {
return null;  // <- See the return
}
} else {
return null;  // <- See the return
}
});

或类似

export const handleTestData = functions.firestore.document('test/{docID}').onCreate(async (snap, context) => {
const data = snap.data();
if (data) {
try {
await admin.firestore().doc('test1/' + context.params.docID + '/').update({duplicate : true});
return null;  // <- See the return
} catch (error) {
return null;  // <- See the return
}
} else {
return null;  // <- See the return
}
});

返回null(或true,或1…(是有效的,因为async函数总是返回Promise。

最新更新