0

I'm adding some keys from a firebase database to an array, but it remains empty. The code is the following:

ref.once("value")
    .then(function(snapshot) { 
      snapshot.forEach(tag =>{
        tags1.push(tag.key);           
      })         
  });

I checked for the value of tag.key by printing it on the console inside the forEach, and all the keys are printed correctly.

Then, I've tried to perform a forEach on the tags1 array, but it doesn't enter the for. I've printed the length of tags1 and it is 0.

I've declared tags1 this way:

let tags1 = [];

I've also tried to declare it as Array<any>, but it keeps staying empty.

Peter B
  • 22,460
  • 5
  • 32
  • 69
Usr
  • 2,628
  • 10
  • 51
  • 91
  • The `tags1` array will not be populated outside the `then` clause. That is fundamental to the notion of asynchrony. This has nothing to do with typescript or ionic or firebase. –  Jun 19 '17 at 10:35
  • Did you mean "`.then(` *I've tried to perform a forEach on the tags1 array* `)`"? – Bergi Jun 19 '17 at 11:27

1 Answers1

2

Let's go over the sequence in which things happen:

const tags1 = [];                     // 1 -- EMPTY

ref.once("value")                     // 2 -- EMPTY
    .then(function(snapshot) { 
      snapshot.forEach(tag => {
        tags1.push(tag.key);          // 4 -- GETS NEW VALUES        
      });
      console.log(tags1);             // 5 -- HAS ALL VALUES
  });

console.log(tags1);                   // 3 -- STILL EMPTY!