0

This was working for me before, but without having changed anything, it seems to have broke. I'm declaring a variable outside of a code block, and then reassigning the value in a loop. The value prints correctly within the loop, but I get an empty string when I print outside the block.

var cnaKey = ""; // Instantiating this variable outside the code block below

var cnaRef = rootRef.child("Activities/"+selectedPatient+"/"+selectedDate);
    cnaRef.once('value', function(cnaSnap){
        cnaSnap.forEach(function(cnaChild) {
            cnaKey = cnaChild.key;
            console.log(cnaKey); // This is printing the correct value 
        });
      });

console.log(cnaKey) // Printing an empty string
  • what is the last value of cnaKey in your loop? It may be printing empty string in console and you might not be noticing it – Vatsal Mar 18 '20 at 17:44
  • 1
    This has nothing to do with scope. It's about time travel. You log the empty string before the function which assigns a different value to it is called. – Quentin Mar 18 '20 at 17:45
  • @Quentin: that seems likely, although I don't know the Firebase API that well. But what does this have to do with the duplicate question you assigned? – Scott Sauyet Mar 18 '20 at 17:46
  • @ScottSauyet — In the duplicate question `return result` executes before `result = response;` for the same reason. – Quentin Mar 18 '20 at 17:48
  • @Quentin. Very weird. When I looked at this a minute ago, the duplicate referred to was https://stackoverflow.com/q/35553500, about CORS policy...some glitch no doubt. – Scott Sauyet Mar 18 '20 at 17:51
  • @ScottSauyet I had the same problem about it referring to CORS policy. I see the correct duplicate question now. Thanks guys! – Sam Dudick Mar 18 '20 at 17:53

0 Answers0