0

I'm looping through a javascript object and doing a $.getJSON call inside an if-else clause.

There's something strange happening so that for some reason $.getJSON seems to be triggered in the else clause instead of the if clause. Here's my code

            for (var subProp in prop.Properties) {
                if (prop.Properties[subProp]['Dependencies'].length == 0) {
                    console.log(prop.Properties[subProp]['Url']);
                    console.log('hi');
                    $.getJSON(prop.Properties[subProp]['Url']).done(function (jsres) {
                        console.log(prop.Properties[subProp]['Url']);
                    });
                } else {
                    console.log('hello');
                }
            }

What happend is that it prints 4 urls in the if clause with the first console.log, but the console.log inside $.getJSON instead prints the other URL where prop.Properties[subProp]['Dependencies'].length > 0, it prints together with console.log('hello'); instead of together with console.log('hi');

If I move $.getJSON to the else clause, it prints the same URL as when it's in the if clause, except when it's in the if clause it gets printed 5 times and when it's in the else clause it gets printed a single time.

edit: so I tried the solution of using let instead of if, but I'm still getting the same result

            for (let i = 0; i < Object.keys(prop.Properties).length; i++) {
                console.log(i);
                let k = Object.keys(prop.Properties)[i];                    
                if (prop.Properties[k]['Dependencies'].length == 0) {
                    console.log(prop.Properties[k]['Url']);
                    console.log('hi');
                    $.getJSON(prop.Properties[k]['Url']).done(function (jsres) {
                        console.log(prop.Properties[k]['Url']);
                    });

                } else {
                    console.log('hello');

                }
            }
J. Margarine
  • 397
  • 1
  • 3
  • 8
  • Probably to do with the async nature of `getJSON`. Also: there's no line `console.log('hi');`. – Andy Nov 19 '18 at 13:54
  • managed to delete the console.log('hi') when I pasted, put it back now – J. Margarine Nov 19 '18 at 13:57
  • Change `var subProp` to `let subProp`. See [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – charlietfl Nov 19 '18 at 13:58

0 Answers0