Mark Dibeh
Mark Dibeh

Reputation: 459

Wait The past function to finish to start a new one

I have 4 Ajax functions the first is independent , but all the other three functions are dependent on the ones before . Real example : I Have Country , Governorate , District , Town and Road the Country can be called directly while all the others have to wait till the ones before
I made sure that all functions are working right and they get data , "so there is no problem with ajax request ". after I have tried those two methods :

$.when(GetCountry()).then(function(){
    GetGovernerate();
}).then(function(){
    GetDistrict(GovernerateID);
}).then(GetTown(DistrictID)).then(function(){
    GetRoad(TownID)
});

I have also tried the done method :

$.when(GetCountry()).done(function(){
    GetGovernerate();
}).done(function(){
    GetDistrict(GovernerateID);
}).done(GetTown(DistrictID)).done(function(){
    GetRoad(TownID)
});

The result is that both of them get the governerate elements and all the rest are not called (resolved). i have looked to the console for any error, but nothing to show .

I did a work around example for it but this is not as productive as call back functions :

setTimeOut(function(){
    GetGovernerate()
},150,function(){
    setTimeOut(function(){
        GetDistrict();
    },150,function(){
        GetTown();
    });
});

I have looked into the explanation of jquery , but am not understanding it . Can any one please make it easier to me to understand .

Upvotes: 1

Views: 74

Answers (1)

Ergec
Ergec

Reputation: 11824

Here is a working code for you. I had to add sleep to simulate ajax delays.

Your problem is you are not returning promises of function calls.

Working Fiddle

//Chain one after another using previous object
$.when(GetCountry()).then(function() {
  return GetGovernerate();
}).then(function() {
  return GetDistrict();
}).then(function() {
  return GetTown();
}).then(function() {
  return GetRoad();
}).done(function() {
  $("body").append("<p>all done</p>");
});

//all needed functions
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

function GetCountry() {
  $("body").append("GetCountry<br>");
  return sleep(1000);
}

function GetGovernerate() {
  $("body").append("GetGovernerate<br>");
  return sleep(1000);
}

function GetDistrict() {
  $("body").append("GetDistrict<br>");
  return sleep(1000);
}

function GetTown() {
  $("body").append("GetTown<br>");
  return sleep(1000);
}

function GetRoad() {
  $("body").append("GetRoad<br>");
  return sleep(1000);
}

Upvotes: 3

Related Questions