[GIS] Waiting on AJAX result in main JS function

ajaxcartojavascriptjquery

So …. my main init()Javascript function has these 3 lines:

sarea =  GetArea(Uname,UIDfield,Table, document.getElementById("Source").value);
darea =  GetArea(Uname,UIDfield,Table, document.getElementById("Destination").value);
alert(sarea);

The GetArea function work as expected, and I use the when/then jQuery technique to wait on the AJAX GET, if I monitor it (alert box) I can see that the value before the return statement is correct.
however, in the init code, an alert that comes after the function, and uses it's return is incorrect, I get undefined.
In addition if I have all three alert boxes I get the undefined one before the other two alert me with the correct result, so the order in the init() function is what's acting funny.

function GetArea(Uname,UIDfield,Table, sourceID){
    var ReqUrl = "http://" +Uname+".cartodb.com/api/v2/sql?q=select ST_Area(the_geom::geography)/1000000 as SA FROM "+Table+" where "+UIDfield+"="+sourceID;
    var area;

    $.when($.ajax({
        async: true,
        type: 'GET',
        url: ReqUrl,
        success: function(data) {
            area = data.rows[0].sa;
        },
        error: function() {
            area = null;
        }
    })).then(function(data) {
        return area;});
}

I know that I could set async: false but that isn't in the spirit of AJAX, their has to be a neat way to do this.

Update

So I got my head around promises and decided to use the then functionality, however it is still not working. I am running out of ideas (read as patience) with my little webpage, this is my new code, It is still not working, I put comments inline to explain.
I really hope i'm missing something obvious here, I really don't think i'm reinventing the wheel

var promise = new Promise(function(resolve, reject) {
GetArea(Uname,UIDfield,Table, document.getElementById("Source").value,function(data) {
  console.log("before callback finishes and before temp is set " + data) //the data passed to the callback looks legit
  temp = data; //wait for the async function to finish and set  a global variable the data passed to the callback.
  console.log("before callback finishes, this is temp " + temp); //the updated temp value looks legit
 });
 if (temp > 0) {
    console.log("after temp is set and before resolve is set " + temp); //hmmm this never fires
  resolve(temp);
}
else {
    console.log("after temp is set and before REJECT is set " + temp); //this fires
  reject(Error("It broke"));
}
});


promise.then(function(result) {
  console.log(result); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"
});

it uses a function stored in another .js file:

function GetArea(Uname,UIDfield,Table, sourceID, callback){
    $.when($.ajax({
        type: 'GET',
        url: "http://" +Uname+".cartodb.com/api/v2/sql?q=select ST_Area(the_geom::geography)/1000000 as SA FROM "+Table+" where "+UIDfield+"="+sourceID,
        success: function(data) {
            area = data.rows[0].sa;
        },
        error: function() {
            area = null;
        }
    })).done(function(data) {
        console.log("View data before callback: " + area);
        callback(area);
    });
}

This is the Chrome console feedback:

after temp is set and before REJECT is set undefined
Compare2.html:76 Error: It broke {stack: (...), message: "It broke"}
Compare2.js:36 View data before callback: 294.602577280986
Compare2.html:58 before callback finishes and before temp is set 294.602577280986
Compare2.html:60 before callback finishes, this is temp 294.602577280986

Best Answer

<script type="text/javascript">

        function checkemail() 
        {


                            // alert(12345);
                             var id = $("#edtid").val();
                            var user_email = $("#user_email").val();
                            // alert (user_email);

                            var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;


                            // alert (12345);
                             if (!filter.test(user_email)) 
                              {
                                  $("#myEmailValid").show();
                                  $("#myEmail").hide();

                                return false;
                              }
                              else
                              {


                            $.ajax({

                             type: "POST",

                             url: "/check_email.php", 

                             data: {user_email:user_email,id: id},


                             async : false,

                             success: function(data)
                             {
                                if(data == 1)
                                {

                                    $("#myEmail").show();
                                    // alert(12345);

                                    returnval = false;
                                }
                                else
                                {
                                    $("#myEmail").hide();
                                    // alert(55555);
                                    returnval = true;
                                }   
                            }
                        });
                            // alert(returnval);
                            return returnval;


                    }
        }
        </script>
Related Question