Firebase的云功能 - 序列化返回值时出错:

Mik*_*keG 15 javascript node.js firebase firebase-realtime-database google-cloud-functions

我有一个云函数,用于交叉引用两个列表,并查找列表中彼此匹配的值.该功能似乎工作正常,但在日志中我一直看到这一点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

    });

});
Run Code Online (Sandbox Code Playgroud)

我试过放在return前面,completionRef.set(matchedContacts);但仍然给我错误.不确定我做错了什么以及如何消除错误.谢谢你的帮助

ste*_*osf 12

当返回Firebase数据库上的多个Promise时,我遇到了完全相同的问题.起初我打电话给:

return Promise.all(promises);
Run Code Online (Sandbox Code Playgroud)

我的promises对象是我正在使用的数组,我正在推送所有需要通过调用执行的作业promises.push(<add job here>).我想这是执行作业的有效方法,因为现在作业将并行运行.

云功能有效,但我得到了你描述的完全相同的错误.

但是,正如迈克尔·布莱(Michael Bleigh)在他的评论中提出的那样,添加then修正问题并且我不再看到这个错误:

return Promise.all(promises).then(() => {
  return true;
}).catch(er => {
  console.error('...', er);
});
Run Code Online (Sandbox Code Playgroud)

如果这不能解决您的问题,可能需要将循环对象转换为JSON格式.这里写的是一个例子,但我没有尝试过:https://stackoverflow.com/a/42950571/658323(它使用的是round-json库).

更新2017年12月:似乎在最新的Cloud Functions版本中,云函数会期望返回值(Promise或值),因此return;会导致以下错误:Function returned undefined, expected Promise or value尽管该函数将被执行.因此,当您不返回承诺并希望云功能完成时,您可以返回一个随机值,例如return true;

  • 非常感谢2017年12月更新! (2认同)

Mic*_*igh 1

尝试:

return verifiedNumsRef.once('value').then(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
    };

    return Promise.all([
      removalRef.set(null), //remove the data at the node that triggered this onWrite function
      completionRef.set(matchedContacts)
    ]).then(_ => true);
});
Run Code Online (Sandbox Code Playgroud)

  • 我在类似的用例中看到完全相同的错误。我在先前包含同一引用的一次(“值”)读取的一系列承诺之后调用数据库引用上的事务。该函数似乎具有预期的效果,但我仍然收到错误。 (5认同)
  • 如果你执行 `return Promise.all([...]).then(function() { return true; });` 会怎么样? (2认同)