2017-08-03 100 views
0

我想恢复现有数据,但Firebase云功能执行循环操作,因此我所做的总结无效。有没有解决我的问题? 谢谢firebase云功能函数循环执行

这在我的屏幕拍摄

数据库建设 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; 
    }); 

回答

0

您安装使用on()方法数据库引用听众。这使得连接监听器:

你的回调函数会被触发的初始数据,并再次 每当数据更改

您应该改用once()

侦听只有一个事件指定事件类型,然后 停止收听

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