0

I want to call a function after receiving value of a variable from firebase database, and then pass that variable for further calculations but value of that variable has passed as "undefined". On setting some Timeout on calculations, do the job, but I want some accurate alternative.

I have used callback, ajax and when-then but none is working.

Below is an example, using callback-

function f2(array){
     // do some task
}

var startingDates=firebase.database().ref('Center/'+$id+'/StartingDates');
var variable=[];

function f1(callback){

    startingDates.on('value',function(snapshot){
        variable=snapshot.val();
    });

    callback(variable);  //variable is passed as "undefined" in f2
}

f1(f2);
Vikash Yadav
  • 713
  • 1
  • 9
  • 29
  • Move the call to `callback` **inside** the `value` event callback. – T.J. Crowder Sep 09 '17 at 14:06
  • Also consider using [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises). – T.J. Crowder Sep 09 '17 at 14:07
  • Can you please elaborate, it's not working – Vikash Yadav Sep 09 '17 at 14:20
  • Then either you haven't moved the callback correctly, or something *else* is wrong, not just the timing of the call to the callback. Use the debugger built into your browser to step through the code to see exactly what's going on. Fundamentally, though, again, in the above the callback is in the wrong place, and again, see the linked question's answers for why. – T.J. Crowder Sep 09 '17 at 14:30
  • 1
    The solution is to call `callback` from within `on()`. So `startingDates.on('value',function(snapshot){ variable=snapshot.val(); callback(variable); });}` – Frank van Puffelen Sep 09 '17 at 14:31
  • thanks a lot,it's working.Can you please send me links or explain for this behavioural change. – Vikash Yadav Sep 09 '17 at 15:17

0 Answers0