Maqsood
Maqsood

Reputation: 389

cascaded calling function jQuery

I want to call the function as shown below

getValueListDataWithScol1(1029).done(function (kvalue) {
  konto = kvalue;
  getValueListDataWithScol1(1033).done(function (mvalue) {
    mws = mvalue;
    getValueListDataWithScol1(1101).done(function (wvalue) {
      wirt = wvalue;
      LoadStaticData();
      LoadGridData();
    });
  });
});

but it is hardcoded I want to do it dynamically depending upon the values in array. For example here its three level if array has 4 element another level should be added and in the final call the two function should be called. I don't know how to achieve it. the reason behind this is I need values of the called function in both load function and getValueListDataWithScol1 is basically callback function

I tried to do it like this but function didn't wait for async call which I know I shouldn't but how to make it wait. I cannot change the call to sync .

function loaddata(ids) {
  var d = new $.Deferred();
  for (var key in ids) {
    getValueListDataWithScol1(ids[key]).done(function (value) {
      lists[ids[key]] = value;
    });  
    delete ids[key];
    loaddata(ids)
  }
  d.resolve(lists);
  return d.promise();
}

Upvotes: 1

Views: 338

Answers (1)

charlietfl
charlietfl

Reputation: 171679

Since your requests don't seem dependent on each other you can map an array of requests and use $.when to run when all requests are resolved.

The arguments in $.when.then will be in same order as original array

var array = [5,2,6,4];

var promiseArrray= array.map(function(num, i){
    console.log('Start request #' , i+1)
    return dummyRequest(num).then(function(res){
          console.log('End request #' , i+1)
          return {num: num, res: res}
    });
});

$.when.apply(null, promiseArrray).then(function(){
   var allResults = [].slice.call(arguments);
   processFinalResults(allResults);

});

function processFinalResults(arr){
   console.log('final results:');
   console.log(JSON.stringify(arr));
}

function dummyRequest(num){
   var promise = $.Deferred();
      setTimeout(function(){
         promise.resolve(num * 100);
      }, num * 200);// alternate delay to shuffle completion order of fake requests 
   return promise;
}
.as-console-wrapper {max-height: 100%!important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Related Questions