0

I have a jQuery .each statement that loops through a set of accordion/panels

$("div.section-data-source").each(function () {
    populateAccordion($(this));
});

For each element, I call a function (populateAccordion) which has an AJAX query with it's own done() callback.

How can I tell my each function to wait until the populateAccordion() function is completed before moving on to the next iteration? Can I have a deferred against the function itself - or is there a way for the function to tell the each to iterate?

function populateAccordion(el) {

    var apiName = el.attr("data-source-api-name");

    $.ajax({
        type: 'GET',
        url: api_URL + apiName + "/" + id,
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function(data) {

        el.parent().find('.data-field').map(function () {
            apiDataField = $(this).attr("data-field");
            var itemValue = getApiDataValue(data, apiDataField, "Date");
            $(this).text(itemValue);
        });
    });
    console.log("FINISHED POPULATE");
};
Mike
  • 2,391
  • 6
  • 33
  • 72
  • Possible duplicate of [Wait until all jQuery Ajax requests are done?](https://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done) – yarwest Mar 12 '18 at 15:07
  • I disagree - I have code against the AJAX call in my function that executes when the AJAX call id done. It is the calling each loop that I need to wait until the function is completed – Mike Mar 12 '18 at 15:08
  • Use `async: false` in your ajax call? – standby954 Mar 12 '18 at 15:10
  • 2
    General advice, always try to avoid ajax in loops. Do one call and loop the result. – Karl-André Gagnon Mar 12 '18 at 15:10
  • @standby954 Probably not a good idea since, as of jQuery 1.8, the use of `async:false` in jQuery.ajax() is deprecated. – Parama Kar Mar 12 '18 at 15:24
  • @ParamaKar didn't know that, I haven't used jquery for years. Thanks for letting me know :) – standby954 Mar 12 '18 at 15:27
  • @Karl-AndréGagnon - I'm not sure what you mean. If I have three or four APIs to call, how do I make one call and loop the result? – Mike Mar 12 '18 at 15:51
  • @Mike well, what I meant was to use the least number of AJAX calls in your code. If you have control of the API, you should allow it to request multiple accordions in one call that return an array and then loop that array in JS. If you don't have control on the API but have a server-side control, you could call an action in your server that calls the API and then your server format the response in an array. In other words, try to use the bare minimum of AJAX call. I am aware that not every situation is the same, hence why the use of "general advice". – Karl-André Gagnon Mar 12 '18 at 16:10

0 Answers0