gpt4 book ai didi

node.js - firebase云函数函数在执行中循环

转载 作者:太空宇宙 更新时间:2023-11-04 02:02:32 26 4
gpt4 key购买 nike

我想恢复现有数据,但 Firebase 云函数会进行循环,因此我所做的求和无效。我的问题有解决办法吗?谢谢

这是我的屏幕截图

数据库 build image ,

日志 image

const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
var db = admin.database();
exports.makePurchaseSummaryAdd = functions.database.ref('/invoice_data/{pushIdInvoice}/item/{pushIdItem}')
.onCreate(event => {
var name = event.data.child('itemName').val();
var quantity = event.data.child('quantity').val();

var ref = db.ref('/invoice_data/' + event.params.pushIdInvoice + '/idUser');
ref.on("value", function(snapshot) {
var refUser = db.ref('/user_data/' + snapshot.val() + '/purchaseSummary/' + name.toUpperCase());
refUser.on("value", function(snapshotUser) {
if (snapshotUser.exists()){
console.log('Ada Data');
var count = snapshotUser.val();
var newCount = quantity + count;
refUser.set(newCount);
console.log('create', count, newCount, name.toUpperCase());
}
else {
console.log('Tidak Ada Data');
}
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
return true;
});

最佳答案

您正在使用 on() 附加数据库引用监听器方法。这使得监听器附加:

Your callback will be triggered for the initial data and again whenever the data changes

您应该使用 once() :

Listens for exactly one event of the specified event type, and then stops listening

您的代码正在循环,因为您附加了一个监听器refUser.on(...),然后更改了回调中该位置的值:refUser.set(newCount);

关于node.js - firebase云函数函数在执行中循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45475686/

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