4
$(document).ready(function(){

    // Global function (will be include in any HTML file)
    function m3_result(size_1, size_2, size_3){
        $.get('http://www.google.com', function(data){
            return data;
        });
    }   

    // Another function
    function calculate(){
        var size_1 = parseFloat($('#add_document_form #size_1').val());
        var size_2 = parseFloat($('#add_document_form #size_2').val());
        var size_3 = parseFloat($('#add_document_form #size_3').val());          
        var ax = m3_result(size_1, size_2, size_3);

        alert(ax); // Here ax return: UNDEFINED  
    }

    // Run
    calculate();
});

Results are "undefined", but I would like that calculate() will wait for m3_result() to execute. I see that here problem is coming when I added $.get(), but its needed...

I have searching for callback() like functions, but none fit to my needs, or I just didnt put that right. Any help will be highly appreciated, thanks.


GET url will be localy and element IDs are also ok.

Lauris Kuznecovs
  • 819
  • 1
  • 12
  • 14

1 Answers1

6

You can't return a result from an asynchronous function, instead you can return a promise to supply that value later, which as it happens is the jqXHR object returned by $.get:

function m3_result() {
     return $.get(...)
}

and do the same in calculate:

function calculate() {
    ...
    return m3_result(...); 
}

and then wait for the result, which will be passed as a parameter to the callback registered with the .done function:

calculate().done(function(result) {
    alert(result);
});
Alnitak
  • 334,560
  • 70
  • 407
  • 495