我有一个云函数,用于交叉引用两个列表并在列表中查找相互匹配的值。该函数似乎工作正常,但是在日志中我一直看到这个 Error serializing return value: TypeError: Converting circular structure to JSON 。这是函数...
exports.crossReferenceContacts = functions.database.ref('/cross-ref-contacts/{userId}').onWrite(event => {
if (event.data.previous.exists()) {
return null;
}
const userContacts = event.data.val();
const completionRef = event.data.adminRef.root.child('completed-cross-ref').child(userId);
const removalRef = event.data.ref;
var contactsVerifiedOnDatabase ={};
var matchedContacts= {};
var verifiedNumsRef = event.data.adminRef.root.child('verified-phone-numbers');
return verifiedNumsRef.once('value', function(snapshot) {
contactsVerifiedOnDatabase = snapshot.val();
for (key in userContacts) {
//checks if a value for this key exists in `contactsVerifiedOnDatabase`
//if key dioes exist then add the key:value pair to matchedContacts
};
removalRef.set(null); //remove the data at the node that triggered this onWrite function
completionRef.set(matchedContacts); //write the new data to the completion-node
});
});
我尝试将 return 放在 completionRef.set(matchedContacts); 前面,但这仍然给了我错误。不知道我做错了什么以及如何消除错误。感谢您的帮助
最佳答案
在返回多个作为 Firebase 数据库事务的 Promise 时,我遇到了完全相同的问题。一开始我在打电话:
return Promise.all(promises);
我的promises object 是我正在使用的数组,我通过调用 promises.push(<add job here>) 推送所有需要执行的作业.我想这是执行作业的一种有效方式,因为现在这些作业将并行运行。
云功能有效,但我遇到了与您描述的完全相同的错误。
但是,正如 Michael Bleigh 在评论中建议的那样,添加 then修复了问题,我不再看到该错误:
return Promise.all(promises).then(() => {
return true;
}).catch(er => {
console.error('...', er);
});
如果这不能解决您的问题,您可能需要将循环对象转换为 JSON 格式。这里写了一个例子,但我没有尝试过:https://stackoverflow.com/a/42950571/658323 (它使用的是circular-json库)。
2017 年 12 月更新:似乎在最新的 Cloud Functions 版本中,云函数需要返回值(Promise 或值),所以 return;将导致以下错误:Function returned undefined, expected Promise or value尽管该功能将被执行。因此,当您不返回 promise 并且希望云功能完成时,您可以返回一个随机值,例如return true;
关于javascript - Cloud Functions for Firebase - 序列化返回值 : 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44790496/