直接从应用程序调用时,云函数返回null

时间:2019-03-21 13:43:12

标签: javascript firebase google-cloud-functions

我正在尝试使用我的应用程序中的Firebase云功能将电子邮件和用户名发布到具有随机生成的ID的Cloud Firestore集合中。一切正常,但是我想从功能中获得对我应用程序的响应,而我实在无法做到这一点。这是我的应用程序中的代码,我将其称为云功能:

onPress ({commit, dispatch}, payload) {
      var addUserInformation = firebase.functions().httpsCallable('addUserInformation');
      addUserInformation(payload)
      .then(function(result) {
        console.log(result)
      }).catch(function(error) {
        var code = error.code;
        var message = error.message;
        var details = error.details;
        console.log(code);
        console.log(message);
        console.log(details);
      });
    },

这是云函数的代码:

    const functions = require('firebase-functions')
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//


exports.addUserInformation = functions.https.onCall((data) => {
    admin.firestore().collection('Backend').where('email', '==', data[1]).get()
    .then(function(querySnapshot) {
            if (querySnapshot.size > 0) {
                console.log('Email already exists')
            } else {
                admin.firestore().collection('Backend').add({
                    name: data[0],
                    email: data[1]
                })
                console.log('New document has been written')
            }
        return {result: 'Something here'};
    })
    .catch(function(error) {
        console.error("Error adding document: ", error);
    })
});

控制台显示结果为空

1 个答案:

答案 0 :(得分:3)

您没有从Cloud Functions代码的顶级返回承诺,这意味着代码结束而不向调用者返回任何内容。

要解决此问题,请返回顶级get的值:

exports.addUserInformation = functions.https.onCall((data) => {
    return admin.firestore().collection('Backend').where('email', '==', data[1]).get()
    .then(function(querySnapshot) {
            if (querySnapshot.size > 0) {
                console.log('Email already exists')
            } else {
                admin.firestore().collection('Backend').add({
                    name: data[0],
                    email: data[1]
                })
                console.log('New document has been written')
            }
        return {result: 'Something here'};
    })
    .catch(function(error) {
        console.error("Error adding document: ", error);
    })
});