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

标签 javascript firebase google-cloud-functions

我正在尝试使用我的应用程序中的 Firebase 云功能将电子邮件和用户名发布到具有随机生成的 ID 的云 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);
    })
});

控制台显示结果为空

最佳答案

您不会从 Cloud Functions 代码的顶层返回 promise ,这意味着代码结束时不会向调用者返回任何内容。

要解决此问题,请返回顶级 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);
    })
});

关于javascript - 直接从应用程序调用时,云函数返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55281822/

相关文章:

javascript - 追加不受 javascript 影响的 jQuery 值

javascript - ASP.NET - 仅在需要时提示确认

javascript - 如何防止提交表单并改为调用 jquery ajax

javascript - ref.once() 未在 Firebase 上调用

java - 为什么我的 Cloud Run - 到 Firebase 调用需要这么长时间?

javascript - Google Cloud Functions 以 : timeout when using Axios 结束

javascript - 在本地测试我的 firebase 身份验证触发器

javascript - 包含复选框列表(自动选中所选框下方的框)

java - 是否可以在不附加任何监听器的情况下读取 Firebase 数据?

javascript - 通过 Google Cloud 功能上传文件时不保存元数据