Home > Back-end >  JavaScript/jQuery: How to run a function after an each() loop has finished?
JavaScript/jQuery: How to run a function after an each() loop has finished?

Time:03-02

I have the following. What is basically happening is I'm prefilling all the dropdowns/select options. I then retrieve the data for the current record and select the appropriate value for each dropdown/select option.

$(dropdowns_sql).each(function (key, value) {
    var sql = value.sql;
    var dropdown = value.dropdown;

    $.post(d   '/inc/db.asp', {
        type: value.sql
    }, function (data) {
        json_object = JSON.parse(data);
    }).done(function () {
        $.each(json_object, function (k, v) {
            $('#'   dropdown).append($("<option></option>").attr("value", v[sql]).text(v[sql]));
        });
    });
});
get_record_data();

My question is how I can ensure that get_record_data(); is run after the loop has finished? As you can see I make POST requests within the loop so what I am finding is that sometimes these don't finish before get_record_data(); is called.

I did try:

$( document ).ajaxStop(function() {
    get_record_data();
});

However since get_record_data(); is doing an AJAX request as well, I am finding it just goes into an infinite loop

function get_record_data() {
    $.post(d   '/inc/db.asp', {
        type: 'get_record',
        id: complex_record_id
    }, function (data) {
...

Any suggestions? I need support for IE11 as well.

Thanks.

CodePudding user response:

Know how many elements are in dropdowns_sql, make a count var and include the get_record_data call within the done function for the last element.

Something like:

var count = dropdowns_sql.length;
$(dropdowns_sql).each(function (key, value) {
    var sql = value.sql;
    var dropdown = value.dropdown;

    $.post(d   '/inc/db.asp', {
        type: value.sql
    }, function (data) {
        json_object = JSON.parse(data);
    }).done(function () {
        $.each(json_object, function (k, v) {
            $('#'   dropdown).append($("<option></option>").attr("value", v[sql]).text(v[sql]));
        });
        if (!--count) get_record_data();
    });
});
  • Related