我有一个可以正常工作的Firebase Cloud功能(它以Admin身份写入我的数据库,并检查具有电子邮件字符串ID的现有条目)。我的问题是,它无法将数据正确地返回到客户端应用程序。
当我跟踪result
的值时,它是{data: null}
如果电子邮件存在,我也想抛出一个错误,但是它抱怨未处理的承诺(请参见下面代码中的注释)。
所以这里有两个问题。首先是最紧迫的。
exports.saveData = functions.https.onCall( (data, context) => {
// check if the email exists
admin.database().ref('competition_entries/' + data.compId + '/' + data.emailStringId).once('value').then(function(snapshot) {
if (snapshot.val() == null){
console.log("Writing data to "+data.compId+" : "+data.emailStringId);
let current_datetime = new Date()
let formatted_time = current_datetime.getHours() + ":" + current_datetime.getMinutes() + ":" + current_datetime.getSeconds();
let formatted_date = current_datetime.getDate() + "/" + (current_datetime.getMonth() + 1) + "/" + current_datetime.getFullYear();
let timestamp_string = formatted_time+" "+formatted_date;
console.log(formatted_date)
admin.database().ref('competition_entries/' + data.compId + '/' + data.emailStringId).set({
name: data.name,
email: data.email,
phone: data.phone,
selectedItem: data.selectedItem,
submitted_date: timestamp_string
})
.then(() => {
console.log("success");
return {
"error": "none",
"message": "success"
};
}).catch(function(error) {
throw error;
});
}else{
// email address exists as a data entry so tell the user that they have already submitted
let code = "already-exists";
let message = "Email address already exists";
let details = "A user with the same email address has already entered the competition.";
console.log(message+"/"+details);
/*
TODO: throwing an HttpsError directly here was causing an unresolved promise error. This would be the better way to tell the client that the user has already submitted their data.
*/
// throw error;
//throw new functions.https.HttpsError(code, message, details);
// this resolves the promise error but is a hack
return {
error: new functions.https.HttpsError(code, message, details),
message: message
}
}
}).catch(function(error) {
throw error;
});
});
答案 0 :(得分:1)
我认为问题是您退回的钱不够。函数需要每个函数返回成功执行的内容。
Commonly是return true
或return Promise
所以应该是这样的:
//check if email exist
return admin.databse...
//If there is no user create it
return.admin...
代码确实写入了数据库,但是由于它不是异步发生的返回,因此代码将自上而下地继续执行,从而使函数能够对客户端做出响应。
您应该
if (!snapshot)
短路比较好,因为快照可能未定义,当checkinf如果快照数据为null时会导致异常