简体   繁体   中英

Wait till function finishes in recursive function

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM