0

My code:

function validateAddress(type){

    var status = true

    if(type == 0 || type == 2){
      $.get( "/user/status/0", function( data ) {
          if(!data.status){
            status = false
          }
          else
            status = true
        });
    }
    else{
      $.get( "/status/1", function( data ) {
          if(!data.status){
            status = false;
          }
          else{
            status = true
          }
        });
    }
    console.log(status)
    return status
  }

How to make sure the internal status is returned from function? At the moment it returns true all the time, because somehow the status value isn't changed. The AJAX part itself is working fine.

seikzer
  • 111
  • 1
  • 1
  • 8

1 Answers1

0

You need to account for the fact that AJAX is asynchronous - your $.get calls don't block, they just queue up events and execution continues right on through your method currently, so it ends up returning the initial value you assign status, true, every time.

You can have your function return an instance of jQuery's Deferred to get around this:

function validateAddress(type){

    var promise = $.Deferred();
    var status = true;

    if(type == 0 || type == 2){
      $.get( "/user/status/0", function( data ) {
          if(!data.status){
            status = false;
          }
          else
            status = true;

          // This is the important bit
          promise.resolve(status);
        });
    }
    else{
      $.get( "/status/1", function( data ) {
          if(!data.status){
            status = false;
          }
          else{
            status = true;
          }

          // This is the important bit
          promise.resolve(status);
        });
    }
    return promise;
  }

Then, when consuming the return value of that function:

validateAddress(someTypeVarPassedInHere)
    .done(function (status) {
        console.log(status);
    });
bsinky
  • 515
  • 5
  • 15
  • Is there a way to make sure the function validateAddress() is returning the value directly, not using the callback, as you did? – seikzer Jan 12 '18 at 13:54
  • @seikzer see [this](https://stackoverflow.com/a/14220323/4276832) and scroll down to "Not recommended: Synchronous "Ajax" calls", as you can see, it is doable but not recommended. – bsinky Jan 12 '18 at 13:58
  • No. With asynchronous code you have to use the callback pattern – Rory McCrossan Jan 12 '18 at 13:58
  • Problem is still existing, even if I use: `$.get( "/user/status/1", {'async' : false}, function( data ) {` – seikzer Jan 12 '18 at 14:38
  • [$.get](https://api.jquery.com/jquery.get/) does not support the `options` that $.ajax does, you will need to write out the full `$.ajax` call to use the `options` if you insist on using synchronous XHR. – bsinky Jan 12 '18 at 17:03