0

I'm using a plugin that has a settings object like this:-

var settings = {
 'onValidate' : myValidationCallback
}

const myValidationCallback= (params) => { 
// return true if ajax is success
// return false if ajax is failed
}

I'm using $.ajax

I understand that $.ajax is an async call. How do i properly use callback here to return true/false?

Here's what i did so far but hit the async code blo

const myValidationCallback= (params) => { 
$.post( "/sample", { name: "John", time: "2pm"})
    .done(function() {
    return true;
    })
    .fail(function() {
    return false;
    }); 
}
Zaiman Noris
  • 322
  • 5
  • 18
  • 1
    You can't return anything from a async function, so the problem is moot. – Rory McCrossan Nov 28 '19 at 08:52
  • Where's Promise here? – Aksen P Nov 28 '19 at 08:56
  • Check this one -> https://stackoverflow.com/a/5316755/2182949 – Goran Stoyanov Nov 28 '19 at 08:58
  • @AksenP $.ajax is a Promise object – Zaiman Noris Nov 28 '19 at 08:58
  • @RoryMcCrossan that's what i'm afraid. How do i implement callback here to suit my usecase? – Zaiman Noris Nov 28 '19 at 08:59
  • @ZaimanNoris, you're really think that? [Promise is an object which is returned by the async function like ajax.](https://medium.com/front-end-weekly/ajax-async-callback-promise-e98f8074ebd7) $.ajax is not a Promise. – Aksen P Nov 28 '19 at 09:02
  • 1
    You can't. If you need an AJAX request to determine the state of the boolean value you need the library you're using to expose methods you can call once the request completes. As that's not the case here, you need to invert the logic so you make the AJAX call first to get the boolean value, and then define the library in the callback of that request – Rory McCrossan Nov 28 '19 at 09:03
  • @AksenP, see the [jquery documentation](https://api.jquery.com/jquery.ajax/) *The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise* – trincot Nov 28 '19 at 09:06
  • @RoryMcCrossan thanks for the insight. i understand your point. – Zaiman Noris Nov 28 '19 at 09:16
  • @trincot, but it [is not the same](https://stackoverflow.com/a/39757547/11607574). – Aksen P Nov 28 '19 at 09:17
  • @Aksen, in that Q&A, the OP was not using the promise interface of `$.ajax`, probably because jQuery 3 had only been out for a few months on that date. That answer is written with the `done` method in mind, and/or the more popular jQuery versions of that day, neither of which implement Promises/A+ compliant behavior. But since jQuery 3, `$.ajax` returns a Promise object. Even though it has more than that, it is a Promises/A+ compliant object, as also announced in the [v3 release notes](https://jquery.com/upgrade-guide/3.0/). – trincot Nov 28 '19 at 09:28

0 Answers0