-1

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?

Sainan
  • 1,274
  • 2
  • 19
  • 32
CMS
  • 285
  • 1
  • 4
  • 10

1 Answers1

0

You can just count how many requests have already been made and since you know how much you need to do in total, you can do something like this:

var reqs_done = 0;
for(var i = 0; i < hosts.length; i++)
{
    // ...
    $.getJSON(...).done(function()
    {
        reqs_done++;
        if(reqs_done == hosts.length)
        {
            // Code when all requests are done ...
        }
    }
}

Note that you should also check for .fail in a productive environment.

Sainan
  • 1,274
  • 2
  • 19
  • 32