1

I'm currently having trouble getting the value from the firebase query below, I'm trying to return an image file from the if statement, but instead, it is returning 'undefined'. I know it is because the value is being returned in the nested firebase function rather the parent 'itemStatus' function.

function itemStatus(key) {

  ref.child(key)
    .once('value')
    .then(function(snapshot) {
        var value = snapshot.val();

        //returns "true" or "false"  
        var status = value.status;

        if (status == "true") {
            return 'success.png';
        } else {
            ...
        }
    });

  //how do I get the values of my if statement here?
}

My question is, how do I return the value outside of the nested query?

I tried wrapping the firebase query in a function and then tried calling it outside but it still returned 'undefined' regardless but I feel I'm going wrong somewhere doing that. I've not had problems with nested functions before but this is really confusing me, I'm guessing it's because the firebase call is asynchronous and that is causing issues somehow but I'm really not sure. Any help would be much appreciated!

JLRishe
  • 99,490
  • 19
  • 131
  • 169
J Bookah
  • 11
  • 1
  • 1
    I wouldn't say this is an "exact" duplicate. Anyway, you want to take advantage of the fact that Firebase 's `.once()` function returns a Promise -> I'd recommend saving the `ref.child(key).once('value')` as a variable, returning that variable in your `itemStatus` function, then in another part of your code, do `itemStatus('your_key').then(function(value){ // your code here});` – Blundering Philosopher Mar 23 '17 at 18:52
  • @RadicalFanatic Brilliant, I'll look into the Firebase documentation for Promises. I've never used them before or really know anything about them so thanks very much for pointing me in the right direction! – J Bookah Mar 23 '17 at 18:56
  • No problem! -> I'd recommend learning about promises in the Stack-Overflow documentation page here: http://stackoverflow.com/documentation/javascript/231/promises#t=201703231903166270517 – Blundering Philosopher Mar 23 '17 at 19:04

0 Answers0