Home > Blockchain >  how can I create a fake promise that answers with a done function?
how can I create a fake promise that answers with a done function?

Time:05-20

I have this code, which does not work if vID=0 because ajax.done does is not a function:

if (vID > 0) {
  var ajax = CallPHP('GET', 'grid_main.php', "idquery=7&trkbid="   vID);   
} else {
  // Here I need a fake ajax so that the following code will work
  var ajax=new Promise();
};

ajax.done(function(data, textStatus, jqXHR) {
 // do something
}

how can I fix it? Thank you

CodePudding user response:

More logical is make a function and call that.

function nextStep(data, textStatus, jqXHR) {
 // do something
}

if (vID > 0) {
  var ajax = CallPHP('GET', 'grid_main.php', "idquery=7&trkbid="   vID).done(nextStep);   
} else {
  nextStep({});
};

You can not use a promise since jQuery's Ajax object is not a promise. It would have to look something like

var ajax = {
  done: function(method) {
    method({});
  }
};

ajax.done(function(data, textStatus, jqXHR) {
  console.log(data);
});

You could use jQuery's deferred

var ajax = $.Deferred().resolve({});

ajax.done(function(data, textStatus, jqXHR) {
  console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related