Vinay
Vinay

Reputation: 93

AJAX - with nested promise

var preadd = $.ajax({
  type: 'POST',
  url: url,
  data: {
    some data
  },
  success: function(output) {

    if (output != 12 && output != 13) {

      some code here...

      var arr = [];
      arr.push.apply(arr, val.split(","));
      arr.splice(-1, 1);
      for (var i = 0; i < arr.length; i++) {
        arr[i] = arr[i].trim();
      }
      chk dup1 is another ajax
      function outside
      var chk = chkdup1();
      console.log(chk);
      chk.then(function() {
        if (result == 13) {

          rem = confirm("Duplicate data will be removed, are you sure!");
          if (rem == false) {
            return false;
          }
          if (rem == true) {
            remdens1();
          }
        }
      });
    }
    if (output == 13) {
      rem = confirm("Duplicate data will be removed, are you sure!");
      if (rem == true) {
        remdens1();
      }
    }

    if (output == 12) {
      $('#valensdata').html("success").css('color', 'green');
    }
    return rem;
  }
});

preadd.then(function() {
  console.log(rem);
  if (rem == false) {
    return false;
  }

  fnensadd();

});
  1. even if i press cancel in confirm inside .then function of preadd,
  2. i am unable to get the value stored inside rem variable.
  3. preadd.then at the bottom function is executing even when return false.

can anyone kindly guide me.

Upvotes: 0

Views: 138

Answers (1)

user1536841
user1536841

Reputation: 146

even if i press cancel in confirm inside .then function of preadd:

     Promise Preadd has no knowledge of cancel. You are returning a value false when cancel is clicked.     

i am unable to get the value stored inside rem variable.

 Assuming rem is a local variable of success function, the variable dies when success function is completed. A bad way of coding would be creating rem in  larger scope , eg sibling of preadd

preadd.then at the bottom function is executing even when return false.

resolveCB of preadd.then( resolveCB, rejectCB) will always be called unless an until there is some error or promise is rejected. Returning false is not same as rejecting promise.   

After saying this ,either use "then" or "success". If you want to Prevent CB Hell, always use promise.

A better code structure with promises would be as follows

var preadd = $.ajax({
   type: 'POST',
   url: url,
   data: {
     some data
  }

preadd.then(function() {
     // Success of PreAdd
          return chkdup1() 
}).then(function(){
    // Success of chkdup1
    //by some internal logic build rem
    if(rem)
    return Promise.resolve(rem )
    return Promise.reject(rem)
}).then(function(data){

     // rem was true
      fnensadd();
},function(error){
    // rem was false

 });

Upvotes: 1

Related Questions