解决一堆承诺时出现Firebase错误:无法将undefined或null转换为对象

时间:2018-01-19 09:19:20

标签: javascript node.js firebase promise google-cloud-functions

我在运行云功能时遇到来自firebase的错误:

  

FIREBASE警告:用户回调引发了异常。类型错误:   无法将undefined或null转换为对象

以下是可能发生错误的代码段:

    // const functions = require('firebase-functions');
    // const admin = require('firebase-admin');
    // const underscore = require('underscore');
    // admin.initializeApp(functions.config().firebase);
    // export updateSimilars = functions.database.ref('...').onWrite(event => {
    ...
        for (var i in callerFlattenLikesDislikes) {
            getOtherUsersPromises.push(getOtherUsersFromName(callerFlattenLikesDislikes[i], genre));
        }    
        console.log('getOtherUsersPromises length: ' + getOtherUsersPromises.length);    
        return Promise.all(getOtherUsersPromises).then(dataArr => {
                    console.log(dataArr); // will never fire
                    dataArr.forEach(data => {
                        data.forEach(user => {
                            if (otherUsers.indexOf(user) > -1 && user !== userId) {
                                otherUsers.push(user);
                            }
                        });
                    });
             ....
             ....

      function getOtherUsersFromName(name, genre) {
       console.log('fired getOtherUsersFromName: ' + name);
       return new Promise((resolve, reject) => {
        admin
            .database()
            .ref('/names/' + genre + '/' + name)
            .once('value', snapshot => {
                var dic = snapshot.val();
                var dislikingUsers = Object.keys(dic['dislikingUsers']);
                var likingUsers = Object.keys(dic['likingUsers']);
                var users = underscore.union(dislikingUsers, likingUsers);
                console.log('will resolve: ' + users);
                resolve(users);
            });
         });
       }

基本上,我有一个异步执行的promise数组(对于几个输入项有相同的firebase查询)。 我想在开始处理之前收集所有结果。

但是.then之后的Promise.all似乎永远不会被解雇,而且我有以下的firebase日志:

enter image description here

有人帮我吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

我认为你需要在路径'/names/' + genre + '/' + name检查名称是否存在。当此路径为空时,它会出错。

function getOtherUsersFromName(name, genre) {
       console.log('fired getOtherUsersFromName: ' + name);
       return new Promise((resolve, reject) => {
        admin
            .database()
            .ref('/names/' + genre + '/' + name)
            .once('value', snapshot => {
               if (snapshot.exists()){
                var dic = snapshot.val();
                var dislikingUsers = Object.keys(dic['dislikingUsers']);
                var likingUsers = Object.keys(dic['likingUsers']);
                var users = underscore.union(dislikingUsers, likingUsers);
                console.log('will resolve: ' + users);
                resolve(users); 
               } else {
                  // Do something as the path is empty
               }
            });
         });
       }