0

So I have a variable list of nodes that I need to query. The list changes given what is online/offline at the time. I need to compile the returned data from all nodes into a single array (dates), but I want to display a loading element until all the requests are complete. I tried understanding/using promises, but couldn't get it to fit what I have since my loop was dynamic. Maybe I just don't fully understand promises yet to be able to implement them, but I just need to find a solution.

$(document).ready(function(){
    dates = [];
    $('loading').show();
    for(let x = 0; x < node_list.length; x++) {

        getDates(node_list[x]); 

    }
    // something here to wait?
    $('loading').hide();
    $('results').show();
});


function getDates(node) {


    var url = 'https://rest.api/' + node;

        jQuery.ajax( {
            url: url,
            method: 'GET',
            dataType: 'json',
            async: true,
            success: function ( data, textStatus, jqXHR ) {
            if ( data.length > 0 ) {

                dates.push(data);
            }
            },
            error: function ( jqXHR, textStatus, errorThrown ) {
                console.log( 'An error has occured! ' + errorThrown );
            }
        });

    return dates;
}
mrpatg
  • 10,001
  • 42
  • 110
  • 169
  • https://api.jquery.com/jQuery.when paired with https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply will let you use `when()` with an array input – Taplar Aug 31 '18 at 17:57
  • Did you know about this wonderful method? `$(document).ajaxStop(function(){ // do something })` – Iskandar Reza Aug 31 '18 at 17:57
  • Side note; `dates` is a global variable, since it is not scoped with `var`, so the fact that `getDates()` returns it at the end (and that that return value is not used), is a code smell. – Taplar Aug 31 '18 at 18:01

0 Answers0