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');
}
}