0

Here is a part of the function I'm working on:

this.instructions is an array.

I've deliberately added some console.log() just to show you that the item I'm looking for in this.instructions array exists.

insertOrUpdateI(i, instruction_frame) {

    if (i.hasOwnProperty('src_id')) {
      let iToUpdateIndex = this.instructions.findIndex(known_i => known_i.src_id == i.src_id);
      console.log('i: ',i)
      console.log('this.instructions: ',this.instructions);
      console.log('iToUpdateIndex: ', iToUpdateIndex);
      if (iToUpdateIndex > -1) {
        let oldInstruction = this.instructions[iToUpdateIndex];
        this.instructions[iToUpdateIndex] = {...i, frame: oldInstruction.frame}; // don't update the frame
        this.reconstructMatchState({
          fetchFromBack: false,
          lastFrame: this.stream.lastCameraFrame,
          applyNow: true
        }).subscribe();
        return
      }
    }
....

Here is the result I get:

i : {subject: "card", player_id: 6547, card_type: "yellow_card", src_id: 1, frame: 5077}

this.instructions: [{subject: "period", name: "period_1", start: 5031, frame: 5031, src_id: -1}, {subject: "card", player_id: 6547, card_type: "yellow_card", src_id: 1, frame: 5077}]

iToUpdateInde: -1

However, I have i.src_id === 1 and there is an item on my array that has a src_id == 1

What am I missing? I would appreciate some help!

Community
  • 1
  • 1
yosra
  • 702
  • 1
  • 11
  • 24

2 Answers2

0

Works for me here's a stackblitz example, try doing another ng serve.

Ala Abid
  • 2,256
  • 23
  • 35
  • I did a new ng serve, and I sent 2 instructions, for the first one I got iToUpdateInde == -1 and for the second one I got iToUpdateInde == 1. – yosra May 09 '19 at 10:02
  • oh, that's weird, I think that should be due to an async call then! check if the instructions array or i it self is retrieved from a Http call, the first one could have failed because it was performed before response is received fromthe http call. – Ala Abid May 09 '19 at 10:07
  • 1
    try doing the console.log() before and after the findIndex() to see your data – Ala Abid May 09 '19 at 10:08
  • so I did the logs correspond exactly to the data I have – yosra May 09 '19 at 10:14
  • and still it's outputting a wrong answer? and the second findIndex() is right? strange – Ala Abid May 09 '19 at 10:16
0

Finally, I've found an answer to my question here: Is console.log async or sync There was nothing wrong with my code, the problem may have come from the version of developer tools I was using.

It seems that console.log() have different behaviors according to the browser we're using and it's version. And sometimes it may have an asynchronous behavior, even though we aren't passing any callbacks inside of it!

yosra
  • 702
  • 1
  • 11
  • 24