0

I have a 2 functions which should call one after the other Like below.

MainFunc().then(DrawChart());

MainFunc() function internally have nested functions like I have mentioned below.

I want MainFuc() to return promise or in other way DrawChart() function should call once the createMultiBatchDropdown() is completed.

I checked some links : Nesting asynchronous jquery promises But I dont want to use any set timeout or delay functions.

I'm new to the concept of this then() and promise() function.Any help will be appreciated.

function MainFunc(){
  var r = $.Deferred();
  var xhr = BatchTypeFilterList(data,id).then(function(res){
     //Logic goes here
     var impactXhr = GetImpactData(id).then(function(result){
         var DropXhr = createMultiBatchDropdown('ImpactBatchSearch',result)
     })
  })
 return r.promise(xhr);
}
function BatchTypeFilterList(){
   var deferred = $.Deferred();
   var xhr = $.ajax({
                  //Ajax Call
              success:function(result){
                   deferred.resolve(result);
                 }
              })
    return deferred.promise(xhr);
}
function GetImpactData(){
   var deferred = $.Deferred();
   var xhr = $.ajax({
                  //Ajax Call
              success:function(result){
                   deferred.resolve(result);
                 }
              })
    return deferred.promise(xhr);
}
function createMultiBatchDropdown(){
  var batchDropDownDeferred = $.Deferred();
  //No ajax call normal jquery logic to form dropdown

  batchDropDownDeferred.resolve(data);
  return batchDropDownDeferred.promise(xhr);
}
sindhu
  • 89
  • 1
  • 11
  • 1
    Possible duplicate of [then() callback firing before promise is resolved in node.js](https://stackoverflow.com/questions/43644230/then-callback-firing-before-promise-is-resolved-in-node-js) – str Aug 30 '18 at 06:50

1 Answers1

0

GetImpactData returns a Promise, but it's not chained with the outer xhr, which means that calling MainFunc will result in a Promise that resolves before createMultiBatchDropdown has been called. Instead, return the Promise created by createMultiBatchDropdown so that it's chained with the whole Promise chain properly. You also need to return impactXhr to complete the chain. Change to:

var xhr = BatchTypeFilterList(data, id).then(function(res) {
  //Logic goes here
  var impactXhr = GetImpactData(id).then(function(result) {
    return createMultiBatchDropdown('ImpactBatchSearch', result);
  })
  return impactXhr;
})
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • No it's not working by the time GetImpactData() function executed meaning once ajax comes to success the DrawChart() is calling then createMultiBatchDropdown( ) is calling – sindhu Aug 30 '18 at 07:34