I have nested for
-loops and an Ajax call to an external URL. I want to use promises, but I do not know where to put them. I need to ensure that all the $.getJSON
-requests have been completed before I output problemHost
.
for (var i = 0; i < hosts.length; i++) {
var obj = hosts[i];
for (var key in obj) {
var attrName = key;
var attrValue = obj[key];
host = obj[key];
console.log(host);
$.getJSON('http://myURL/get/', {
uid: host + "." + domain,
last: 1
}, function(data) {
json = data;
for (var i = 0; i < json.length; i++) {
var obj = json[i];
for (var key in obj) {
var attrName = key;
var attrValue = obj[key];
if (key.includes("JFSFILE_")) {
var newkey = key.replace("JFSFILE_", "");
console.log(newkey + " " + obj[key]);
if (parseFloat(obj[key]) > 20) {
if (typeof problemHost[host] == 'undefined') {
problemHost[host] = {};
}
problemHost[host][newkey] = obj[key];
}
}
}
}
});
}
}
This should not execute until all Ajax calls are complete:
if (problemHost.length > 0) {
console.log(problemHost);
}
Where do I put the promises in? Is this the best way to tackle this?