Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading