Javascript Firebase函数-在用户获取内部获取实时数据库后返回
我有一个Firebase云函数,它在我的应用程序中通过JavaScript调用。 调用该函数时,它会从用户ID中获取用户数据,然后从实时数据库中获取记录以检查是否匹配 此函数可以工作,但返回“null”并提前完成,而不是在检测到匹配时返回成功或错误消息 如何使返回文本成为匹配的成功或错误,并且仅在确定此匹配后完成Javascript Firebase函数-在用户获取内部获取实时数据库后返回,javascript,node.js,firebase,firebase-realtime-database,google-cloud-functions,Javascript,Node.js,Firebase,Firebase Realtime Database,Google Cloud Functions,我有一个Firebase云函数,它在我的应用程序中通过JavaScript调用。 调用该函数时,它会从用户ID中获取用户数据,然后从实时数据库中获取记录以检查是否匹配 此函数可以工作,但返回“null”并提前完成,而不是在检测到匹配时返回成功或错误消息 如何使返回文本成为匹配的成功或错误,并且仅在确定此匹配后完成 exports.matchNumber = functions.https.onCall((data, context) => { // ID String passed fro
exports.matchNumber = functions.https.onCall((data, context) => {
// ID String passed from the client.
const ID = data.ID;
const uid = context.auth.uid;
//Get user data
admin.auth().getUser(uid)
.then(function(userRecord) {
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("path/to/data/" + ID);
return ref.on("value", function(snapshot) {
//Fetch current phone number
var phoneORStr = (snapshot.val() && snapshot.val().phone) || "";
//Fetch the current auth user phone number
var userAuthPhoneNumber = userRecord.toJSON().phoneNumber;
//Check if they match
if (userAuthPhoneNumber === phoneORStr) {
console.log("Phone numbers match");
var updateRef = db.ref("path/to/data/" + ID);
updateRef.update({
"userID": uid
});
return {text: "Success"};
} else {
console.log("Phone numbers DO NOT match");
return {text: "Phone number does not match the one on record."};
}
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
return {text: "Error fetching current data."};
});
})
.catch(function(error) {
console.log('Error fetching user data:', error);
return {text: "Error fetching data for authenticated user."};
});
});
谢谢Firebaseref.on()
方法没有返回承诺,因此您在其中的返回
语句没有任何作用
您正在寻找ref.once()
,它返回一个承诺,因此将冒泡出其中的return
语句:
return ref.once("value").then(function(snapshot) {
...
正如Doug所指出的,您还需要从顶层回报承诺。因此:
//Get user data
return admin.auth().getUser(uid)
.then(function(userRecord) {
最重要的是,它们甚至没有从顶级函数返回值。@FrankvanPuffelenThank非常感谢您的帮助!