我遇到了问题。我正在编写一个方法,首先检查用户是否存在并带有条件,如果不存在,它将插入操作,并且我正在使用标志变量来控制流程。但有一个问题,异常不是按顺序出现的,而是先下降,然后 if(!flag) 上升,检查用户是否存在
analysis = actionid => {
//check if it is't the first command
console.log("before definition of flage");
var flag = false;
console.log("hiii");
firebase
.database()
.ref("userActions/")
.once("value", snap => {
console.log("iafter definition ");
snap.forEach(child => {
if (
child.val().userID === firebase.auth().currentUser.uid &&
child.val().ActionID == actionid
) {
plus = parseInt(child.val().Repetition) + 1;
console.log("before first use");
flag = true;
firebase
.database()
.ref(child)
.set((Repetition = plus))
.then(() => {
console.log("inserted the update");
})
.catch(error => {
console.log(error);
});
}
});
});
console.log("before second use");
if (!flag) {
console.log("inside second use");
var userActionKey = firebase
.database()
.ref()
.child("userActions")
.push().key;
firebase
.database()
.ref("userActions/" + userActionKey)
.set({
userID: firebase.auth().currentUser.uid,
ActionID: "001",
time: "12",
Repetition: "1"
})
.then(() => {
console.log("inserted");
})
.catch(error => {
console.log(error);
});
}
};
最佳答案
JavaScript 同步运行代码。要解决该问题,您可以使用 promises
或 async-await
异步运行代码。或者您可以在第一个进程中调用一个函数。
下面的代码应该可以工作。
function doSomething() {
var userActionKey =firebase.database().ref().child('userActions').push().key;
firebase
.database()
.ref('userActions/'+userActionKey)
.set({
userID:firebase.auth().currentUser.uid,
ActionID:'001',
time:'12',
Repetition:'1',
}).then(() => {
console.log('inserted')
}).catch((error)=> {
console.log(error)
});
};
firebase.database().ref('userActions/').once ('value',(snap)=>{
snap.forEach((child)=>{
if(child.val().userID===firebase.auth().currentUser.uid && child.val().ActionID== actionid) {
plus=parseInt(child.val().Repetition)+1;
firebase
.database().ref(child).set(Repetition=plus)
.then(() => {
console.log('inserted the update');
}).catch((error)=>{
console.log(error);
}).finally(() => {
doSomething();
});
}
});
});
我希望这个例子能向您展示逻辑。
我强烈建议您学习 JavaScript 中的promises
。
关于javascript - 如何在 JavaScript 中顺序执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60764731/