0

I am filling an array with test data in this example so I know the firebase data isn't to blame.

this.lastMessages = new Array();

ref.limitToLast(1).on("child_added", (snapshot) => {
   this.zone.run(() => {
       this.lastMessages.push("test");
   });
});

console.log(this.lastMessages);
console.log(this.lastMessages[1]);
console.log(this.lastMessages.length);

In this example I just push the value "test" into the lastMessages array to make it easier. Now I have 3 logs on the bottom which gives weird results.

The first one logs as expected:

[]
0: "test"
1: "test"
2: "test"
length: 3
__proto__: Array(0)

The second log returns undefined and the last log gives me 0 back as length. I made sure by pushing values it does not become associative. Now it couldn't be because it is running in zone since the first console log gives me the right representation. What is going on?

DaViDa
  • 641
  • 1
  • 8
  • 28
  • what is `ref.limitToLast(1)`? – Max Koretskyi Aug 07 '17 at 14:16
  • This is a call to firebase to give me the last entry of a firebase database model. I am not doing anything with firebase data in this example but still showing the function since it does push values within it – DaViDa Aug 07 '17 at 14:18
  • A Side Note: Please be aware of the Nested Arrow function with `this`. Arrow function binds the `this` reference to the lexical scope, which can be an issue with Nested Arrow functions. – Abhinav Galodha Aug 07 '17 at 14:19
  • Is there a chance that your on("child_added"... zone.run(...) is running after your console.log()? It looks like this is an event driven system, that depends on the events running before the code after it. – Jordan Aug 07 '17 at 14:19
  • Yet another synchronous check over an array which is expected to get populated asynchronously. Duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Redu Aug 07 '17 at 14:29
  • 1
    Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Redu Aug 07 '17 at 14:30

1 Answers1

1

This is a combination of expecting aync to be sync and the chrome developer tools showing the reference array.

the ref.limitToLast(1).on makes the whole 'adding' process async, which means that when you log the array there are no elements in it yet, because the async part has not fired yet. Check it by placing a console.log above the this.lastMessages.push. You will see that the logging of 'add' is done after the logging of the array

The reason it does show 3 items is because of a browser optimization. Read here for more details

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149