0

Given I have a recursive method:

tests = {
  add: function (data, option, dataSet) {
    if(option) {
      dataSet.forEach(function (values) {
        this.add(values.data, false);
      }, this);
    }
    console.log(data.name)
  }
}

And I would call this by using

tests.add({name: 'test1'}, true, [{data: {name: 'test2'}}]);

I assume this would log 'test2' before 'test1' in all cases, but in a lot of cases this does not happen. As far I know the forEach function should be blocking the execution of other lines, but this simply does not happen.

Bit of context: The code should add certain components on a webpage. Those components can depend on other components (which are in dataSet). These dependencies should always be recursively added first.

Any ideas?

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
Sebass van Boxel
  • 2,514
  • 1
  • 22
  • 37

1 Answers1

0

The reason for this inconsistency is that console.log is not a synchronous function. Read more here

Community
  • 1
  • 1
Ronen Cypis
  • 21,182
  • 1
  • 20
  • 25
  • I've never seen a `console.log` implementation that shows the logged values out of order. This is not what the answers to the question you linked say. – Bergi Feb 03 '16 at 13:09
  • @Bergi, you can check the last answer in the link i provided, and understand how sometime `console.log` shows you the object the way it looks in the moment of the actual "printing", and not the way it looked when you actually called `console.log`... @Sebass here said that the result is not consistent, and the asynch nature of `console.log` is IMHO a good direction to explore. – Ronen Cypis Feb 03 '16 at 14:43
  • Well sure that's what can happen to objects, but the example snippet the OP gave a) logs string values b) never modifies any object properties – Bergi Feb 03 '16 at 14:46