0
function getoilnum(key){
  var num;
  var eRef = database.ref('dev_story/' + key + '/related_oils');
  eRef.on('value', function(snapshot){
    num = snapshot.val().length;
  })
  return num
}

Hi, there

I'm new to javascript, so I have a question. in this code, I have to get the value of num inside eRef as return value. But this code still prints 'undefined'.

How should I change this code?

  • Have a look at either _Promises_ or _Callbacks_ – JanS Jan 24 '18 at 09:56
  • `on` defines an *event handler* (presumably). That means, that event handler will get called *if and when the event happens.* That may be at any later time *or never.* You can't return its value from a synchronous function call. – deceze Jan 24 '18 at 10:02

0 Answers0