0

i have an easy Ajax request who return true or false according to the result, like this :

function myRequest(){
    $.ajax({
         url: "/",
         method: "GET",
         contentType: "application/json",
         dataType: 'json',
    }).done(function (data) {
         if (data['code'] !== "success") {
              return false;
         }
         else {
              return true;

    }}).fail(function (xhr, textStatus, errorThrown) {
              return false;
    });
}

if(myRequest()){
//do someting
}

When myRequest() is executed for the if statement, it's doesn't wait the Ajax result and is never validate. I read about promise here and i tried but it still the same issue.

Ty !

[EDIT]

So i follow your replies and i just retry with promises. It's work better :

function myRequest(){
   return new Promise((resolve, reject) =>{
        $.ajax({
             url: "/",
             method: "GET",
             contentType: "application/json",
             dataType: 'json',
        }).done(function (data) {
             if (data['code'] !== "success") {
                  resolve(false);
             }
             else {
                  resolve(true);

        }}).fail(function (xhr, textStatus, errorThrown) {
                  rejected(errorThrown);
        });
      });
    }

myRequest().then(function (val) {
    if(val){
       return true;
    }
});
ebillis
  • 224
  • 1
  • 4
  • 19
  • 1
    `myRequest` doesn’t return anything. The `return` statements are within a different function. Learn how to use jQuery’s [`done`](https://api.jquery.com/deferred.done/), and asynchronous functions in general, properly. – Sebastian Simon Aug 24 '18 at 14:11
  • 3
    Short version: `"do something"` should be invoked in your `.done()` handler function, not outside of the AJAX call entirely. You're placing an order for a pizza and then trying to eat the pizza the moment you hang up the phone. Your pizza hasn't arrived yet. – David Aug 24 '18 at 14:16
  • Thanks for you replies, i read other documentations about promises and did a working code. You can check it in my post – ebillis Aug 24 '18 at 15:07

0 Answers0