Home jquery get return inside value to outer funtction
Reply: 1

jquery get return inside value to outer funtction

seikzer
1#
seikzer Published in 2018-01-12 13:41:43Z

This question already has an answer here:

  • How do I return the response from an asynchronous call? 26 answers
  • Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference 6 answers

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.

bsinky
2#
bsinky Reply to 2018-01-12 13:50:09Z

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);
    });
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.309533 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO