我正在尝试使用Firebase编写应用程序。我想将JSON搜索对象存储在searches/
中,并将它们的每个引用存储在属于进行搜索的用户的表中。这是我的尝试:
var firebase = require("firebase");
firebase.initializeApp(firebaseConfig);
var database = firebase.database();
/*
* Inserts a search into the database
*/
this.addSearchToDB = function(positive, negative, neutral){
let today = new Date();
let dateCreated = today.getFullYear()+"-"+(today.getMonth()+1)+"-"+today.getDate();
var search = {
"query": searchInput,
"location": location,
"until": date,
"dateCreated": dateCreated,
"amount": tweetAmount,
"positive": positive,
"negative": negative,
"neutral": neutral
};
//setup of path to reference the data
var searchesRef = database.ref("searches");
var newSearchKey = searchesRef.push(search).key;
console.log("newSearchRef key:");
console.log(newSearchKey);
let user = firebase.auth().currentUser;
let uid = user.uid;
console.log("Curr user id: "+uid);
let userRef = database.ref("users/"+uid);
let currUserSearches;
userRef.once("value").then( (value) => {
currUserSearches = value;
});
console.log("Current user searches");
console.log(currUserSearches);
if (currUserSearches === undefined)
currUserSearches = [];
currUserSearches.push(newSearchKey);
userRef.set(currUserSearches).then( () => {
database.ref("users/"+uid).once("value").then((value)=>{
console.log(value.val());
});
});
}
在第一次插入时,会发生以下情况:
我得到一个
newSearchKey
(成功登录到控制台)我得到
currentUser
的用户ID(成功登录到控制台)currUserSearches
未定义。 (将undefined
记录到控制台)在
userRef.set()
回调中,找到包含newSearchKey
的列表并将其打印到控制台。一切都很好。这是我对第一次插入的期望。但是,当我再次插入时,完全重复相同的过程,这意味着
currUserSearches
再次未定义。这当然是错误的。 currUserSearches
应该包含我刚刚插入的密钥。但似乎忘记了我插入的内容。这是怎么回事,如何实现所需的行为?
最佳答案
这是因为对Firebase数据库的所有查询(读写)都是异步的。在userRef.once("value")
返回结果之前执行console.log#3。
您应该按如下方式链接诺言:
let userRef = database.ref("users/"+uid);
let currUserSearches;
userRef.once("value")
.then( (value) => {
currUserSearches = value;
if (currUserSearches === undefined)
currUserSearches = [];
currUserSearches.push(newSearchKey);
return userRef.set(currUserSearches);
})
.then( () => {
return database.ref("users/"+uid).once("value"); // <- Actually could be userRef.once("value")
})
.then((value)=>{
console.log(value.val());
});