user4363266
user4363266

Reputation:

code after the $.each execute before the function finished executing

I have an function inside it i am using $.each method. I want to call another function alertMsg() after $.each completely executed. But when i use breakpoints i can see that before finishing the $.each method it executes the alertMsg function. why? how to solve it.

   function test(hospitalJson,blockJson){

    $.each(hospitalJson.organisationUnits, function (i, curr_hos) {

        if (curr_hos.id == orgUnit.id) {
            var stringPath=[];
            stringPath= curr_hos.path.split("/");
            outerloop:
                    for(var i=0;i<stringPath.length;i++){
                        for(var j=0;j<blockJson.length;j++){
                            if(stringPath[i]==blockJson[j].id){
                                document.getElementById('blockID').innerHTML = blockJson[j].id;
                                break outerloop;
                            }
                        }

                    }

            // to get district name
            var districtNameURL="../api/organisationUnits.json?fields=name&filter=id:in:[" + curr_hos.path.split("/")[4] + "]" ;

            $.get(districtNameURL,function(district){
                districtName=district.organisationUnits[0].name;
                console.log(districtName);
                document.getElementById('districtID').innerHTML = districtName;
            });

            alertMsg = 1;
            return false;
        }


    });
    //this message execute before finishing $.each
    alert(alertMsg);
}

Upvotes: 0

Views: 75

Answers (2)

Steve Harris
Steve Harris

Reputation: 5109

Change:

        $.get(districtNameURL,function(district){
            districtName=district.organisationUnits[0].name;
            console.log(districtName);
            document.getElementById('districtID').innerHTML = districtName;
        });

To:

        $.ajax({
            url: districtNameURL,
            type: "GET",
            async: false
        })
        .success(function (district) {
            districtName = district.organisationUnits[0].name;
            console.log(districtName);
            document.getElementById('districtID').innerHTML = districtName;
        });

This will stop the get action being asynchronous and therefore your logic will be processed in the expected order.

Upvotes: 0

vorillaz
vorillaz

Reputation: 6266

Due to the fact that $.each has multiple AJAX calls inside, you need to create an array containing Promise objects that need to be resolved . Since you may not know the exact size of the parsed JSON object and jQuery $.when cannot handle arrays you need to extend it's functionality.

function test(hospitalJson, blockJson) {
  var deferreds = [];

  $.each(hospitalJson.organisationUnits, function(i, curr_hos) {

      //...
      deferreds.push(
        $.get(districtNameURL, function(district) {
          districtName = district.organisationUnits[0].name;
          console.log(districtName);
          document.getElementById('districtID').innerHTML = districtName;
        }));
    }
    return deferreds;

  });
}


var resolveData = test(hospitalJson, blockJson);
$.when.apply(null, resolveData).done(function() {
  alert(alertMsg);
});

JSfiddle demo

Upvotes: 1

Related Questions