javascript - 直接从应用程序调用时,云函数返回 null
问题描述
我正在尝试使用我的应用程序中的 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 代码的顶层返回承诺,这意味着代码结束时不会向调用者返回任何内容。
要解决此问题,请返回顶级 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);
})
});
推荐阅读
- c# - UI上的Unity3D粒子系统不会在构建中显示
- c++ - 如何使用 if else 和函数在 C++ 中制作计算器?
- javascript - 如何使用 javascript、php 在 mxgraph 中的工作流编辑器中使用 xml 数据绘制图形
- javascript - 如何以最佳方式验证 joi 子模式
- r - 按值解构向量
- wordpress - 古腾堡区块验证失败(不期待孩子)
- python - Niumpy:将 numpy 2d 数组转换为 3d
- bundle - 如何“要求捆绑”目录中可用的所有捆绑包
- java - 使用 java-streams 进行数据压缩
- java - 如何引用正在创建的对象?