0

Currently, I struggle with some weird js array behavior, which is new to me. Would be great if someone can help me out with that. So this is my code:

getData(strings) {
    let unsortedKeys = ['key1', 'key2'];

    strings.forEach(data => {
      ref.once("value").then(data => {

        // doesn't matter what will be pushed to the array
        unsortedKeys[2] = 'key3';

      });
    });

    return unsortedKeys;
}

I know this code will not work. I've simplified the Firebase promise for this example. By the way, I'm using Angular with Typescript.

The result:

console.log(getData());

enter image description here

If i know iterate over the array just the values of [0] and [1] will be shown. Also accessing the field via index getData()[2] is not possible. I'm not sure if this happens cause the async behavior of promises, but it seems really strange to me, since the value and the index are there.

Does anyone have an idea why this happens?

Orlandster
  • 4,706
  • 2
  • 30
  • 45
  • It's an asynchronous API. The function passed to `.then()` will be called after a period of time, though `.then()` returns immediately. – Pointy Aug 14 '17 at 12:46
  • @Pointy that's what I was expecting. But do you know why is the value there? – Orlandster Aug 14 '17 at 12:49
  • You are not pushing anything ;) you are trying to add a value to a non exiting place in the array. You should do: `unsortedKeys.push('key3');` and it should work. – David Gatti Aug 14 '17 at 12:49
  • The console screenshot shows a lot: at the time it's logged, the array only has two things in it. But when you expand it to look further it evaluates it again and by that point all three items are in the array. – meta Aug 14 '17 at 12:51
  • `return unsortedKeys` will not return anything more than unsortedKeys' initial value. – Redu Aug 14 '17 at 12:54

0 Answers0