[英]Firebase cloud function not returning a value, return data is always null
[英]cloud functions firebase return value is always null?
我在 firebase 中使用了雲 function
function 的想法是為 session 設置領導者,如果沒有領導者,則返回領導者的用戶 ID 我使用 javascript
它總是返回 null 即使我返回snapshot.val
或 function 接收的用戶 ID
console.log(snapshot.val)
給我 [object Object]
代碼
exports.SetLeader = functions.https.onCall((data, context) => {
userID = data.ID
sessionID = data.text
sessionref = "/Sessions/".concat(sessionID);
sessionref = sessionref.concat("/Leader");
var db = admin.database();
var ref = db.ref(sessionref);
console.log("ID" + userID)
ref.once("value", function (snapshot) {
console.log("snapchot"+ snapshot.val()); //x
if (snapshot.val() == null) {
admin.database()
.ref(sessionref).update({ userID })
console.log("inside if " + userID)
return { leader: userID };
}else{
console.log("inside else " + snapshot.val())
return { leader: snapshot.val()};
}
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
});
正如Callable Cloud Functions 的文檔中所解釋的,“要在異步操作后返回數據,請返回 promise ”。 通過使用once()
方法的“回調版本”,您不會返回 Promise。
您應該使用“承諾版本”,如下所示:
return ref.once("value")
.then(snapshot => {...});
此外,由於您必須處理不同的情況,根據快照的值,在您的 Cloud Function 中使用async/await
更具可讀性。 因此,以下應該可以解決問題(未經測試):
exports.SetLeader = functions.https.onCall(async (data, context) => {
try {
const userID = data.ID
const sessionID = data.text
const sessionref = `/Sessions/${sessionID}/Leader` // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const db = admin.database();
const ref = db.ref(sessionref);
console.log("ID" + userID)
const snapshot = await ref.once("value");
console.log("snapchot" + snapshot.val());
if (snapshot.val() == null) {
await admin.database().ref(sessionref).update({ userID })
console.log("inside if " + userID)
return { leader: userID };
} else {
console.log("inside else " + snapshot.val())
return { leader: snapshot.val() };
}
} catch (error) {
// See https://firebase.google.com/docs/functions/callable#handle_errors
// for more fine grained error management
console.log(error);
return null;;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.