Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
JavaScript/jQuery: How to run a function after an each() loop has finished?

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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();
    });
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda