gpt4 book ai didi

javascript - Firebase 触发器功能交替工作

转载 作者:行者123 更新时间:2023-12-03 02:01:39 25 4
gpt4 key购买 nike

我编写了这个 Firebase 函数,该函数在添加数据时触发,它会汇总子值并更新总值字段。

    export const updateTotalAnswersCounts = functions.database
.ref('/CurrentGame/answers/{aid}').onWrite((change, context) => {
var collectionRef = change.after.ref.parent;
let total = 0;
collectionRef.once('value',(snapshot)=>{
console.log('snapshot',snapshot.val())
snapshot.forEach((childSnapshot)=>{
if(childSnapshot.val()!=null){
console.log('childSnapshot',childSnapshot.val())
total+=Number(childSnapshot.val())
}
return false;
})
const updates = {}
updates['/totalAnswersCount'] = total;
firebase.ref('/CurrentGame').update(updates)

})

return true;


});

当我向“answers”节点添加新值时,函数触发器就会工作,然后它会获取所有数字(在这张照片中为 1+2+11),然后将 TotalAnswersCount 更新为总和 = 14。

此添加操作

addAnswer() {
let answer = 3;
let userInfo = {
uid: this.uid,
gid: '1',
qid: '2',
aid: '3'
}
const answer_ref = firebase.database().ref(`CurrentGame/answers/${answer}`);
const users_answers_ref = firebase.database().ref(`GameQuestionStats/${this.user.uid}/${userInfo.qid}`);

// Return the promise from countRef.transaction() so our function
// waits for this async event to complete before it exits.
return answer_ref.transaction((current) => {
return (current || 0) + 1;
}).then(() => {
return users_answers_ref.set(userInfo,{merge:true})
});
}

enter image description here

此 Firebase 功能交替工作

  1. 当我第一次加载应用程序时,它会更新节点,但不会进行任何更新。
  2. 有时会出现延迟,并在 3-4 秒后更新。
  3. 有时它会实时更新并且工作正常。

最佳答案

原因是您必须链接 Promise(因此在每个链接步骤返回一个 Promise)。

以下应该有效:

export const updateTotalAnswersCounts = functions.database
.ref('/CurrentGame/answers/{aid}').onWrite((change, context) => {
const collectionRef = change.after.ref.parent;
let total = 0;

return collectionRef.once('value', (snapshot) => {

console.log('snapshot', snapshot.val())

snapshot.forEach((childSnapshot) => {
if (childSnapshot.val() != null) {
console.log('childSnapshot', childSnapshot.val())
total += Number(childSnapshot.val())
}
})

}).then(() => {
const updates = {}
updates['/totalAnswersCount'] = total
return firebase.ref('/CurrentGame').update(updates)
}).catch(error => {
console.log(error);
//Error treatment
});

});

我建议您观看 Doug Stevenson 关于该主题的视频:

https://www.youtube.com/watch?v=7IkUgCLr5oA&t=515s

https://www.youtube.com/watch?v=652XeeKNHSk

https://www.youtube.com/watch?v=d9GrysWH1Lc&t=4s

请注意,当您不在云函数中返回 promise 时,情况 nbr 2(它有延迟并在 3-4 秒后更新)是一种经典行为。

关于javascript - Firebase 触发器功能交替工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49981104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com