[英]Firebase run set query after get query
由於firebase異步運行,我如何在從get查詢中接收數據並在設置之前檢查它是否存在之后運行set查詢?
var db = firebase.firestore();
db.settings({});
const usersRef = db.collection('users').doc(user.uid)
usersRef.get()
.then((docSnapshot) => {
if (!docSnapshot.exists) {
usersRef.set({
name: '',
email: '',
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
});
提前致謝
如果這是異步的,則可以使用異步並等待。
firebasefunc = async () => {
var db = firebase.firestore();
db.settings({});
const usersRef = db.collection('users').doc(user.uid)
let docSnapshot = await usersRef.get()
if (!docSnapshot.exists) {
await usersRef.set({name: '', email: ''})
}
}
您應該返回set()
方法返回的Promise,以便正確地鏈接您的Promise。
使用您的代碼,最有可能執行set()
但是您看不到console.log("Document successfully written!");
最后,請注意,當快照確實存在時,應處理這種情況,例如,拋出錯誤。
因此,以下代碼可以解決問題:
usersRef.get()
.then((docSnapshot) => {
if (!docSnapshot.exists) {
return usersRef.set({
name: '',
email: '',
});
} else {
throw new Error("Document already exists");
}
})
.then(function () {
console.log("Document successfully written!");
})
.catch(function (error) {
console.error("Error writing document: ", error);
});
從您的評論看來,您似乎是從某個地方調用此代碼,然后應該在繼續執行其他操作(如更改屏幕)之前采取一些后續措施。
為此,您需要從方法中返回一個Promise,以便調用者可以等待get
和set
完成:
function writeUserDocIfNonExistent() {
return usersRef.get()
.then((docSnapshot) => {
if (!docSnapshot.exists) {
return usersRef.set({
name: '',
email: '',
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
else {
return true
}
});
}
現在,您可以調用此函數,並在數據庫操作完成后執行以下操作:
writeUserDocIfNonExistent().then(function() {
console.log("All database interaction is done, let's go...");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.