我正在尝试使用firebase编写应用程序。我想在searches/
中存储JSON搜索对象,并在属于进行搜索的用户的表中对它们中的每一个进行引用。这是我的尝试:
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
应包含我刚刚插入的密钥。但它似乎忘记了我插入的内容。
这里发生了什么,我怎样才能实现我想要的行为?
答案 0 :(得分:2)
这是因为对Firebase数据库的所有查询(读取和写入)都是异步的。 console.log#3在userRef.once("value")
返回结果之前执行。
你应该将承诺链接起来,如下所示:
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());
});