javascript - Passing callback twice in single function in NodeJS -
i have created function fetch values firebase. variables in stored result of firebase query accessible inside firebase operation. require variables outside function created callback function overcome problem.
my code looks this: have 2 firebase databases. 1 store registered users (ref1) , 1 store paid users(paidref). need check 1 has login registered user or paid user.
var paidref=new firebase("https://app.firebaseio.com/paidusers"); var ref1=new firebase("https://app.firebaseio.com/tempuser"); function checkpaidusers(res,callback){ ref1.orderbychild('userid').equalto(jsondata.userid).once('child_added', function(snap) { registereduser=true; paidref.on('child_added',function(snapshot) { if(snapshot.child('userid').val()==jsondata.userid ) { paidflag=true; return callback(registereduser,paidflag,res); } else { paidflag=false; return callback(registereduser,paidflag,res); } }) }) } checkpaidusers( res,function(registereduser,paidflag) { if(registereduser!=true) { newuser=true; } return res.send({paidflag:paidflag,registereduser:registereduser,newuser:newuser});})
this code gives error below:
can't set headers after sent.
this error coming because callback function called many times no. of children paidref has because in case user not found in paidref database goes else block , execute callback function. whats best possible way solve problem of getting information of registered users paid users single callback function.
your issue calling callback once every user in paidref, doesn't seem intention.
code should call callback once.
var paidref=new firebase("https://app.firebaseio.com/paidusers"); var ref1=new firebase("https://app.firebaseio.com/tempuser"); function checkpaidusers(res,callback){ ref1.orderbychild('userid').equalto(jsondata.userid).once('child_added', function(snap) { registereduser=true; paidref.child(jsondata.userid).once('value', function(snapshot) { var paidflag = false; if (snapshot.val() !== null) { paidflag = true; } callback(registereduser, paidflag, res) }) }) } checkpaidusers( res,function(registereduser,paidflag) { if(registereduser!=true) { newuser=true; } return res.send({paidflag:paidflag,registereduser:registereduser,newuser:newuser});})
Comments
Post a Comment