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.

4

1 に答える 1

6

非同期関数から結果を返すことはできません。代わりに、後でその値を提供するという promisejqXHRを返すことができます$.get

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

計算で同じことを行います:

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

.done結果は、関数に登録されたコールバックにパラメーターとして渡されます。

calculate().done(function(result) {
    alert(result);
});
于 2013-07-26T10:46:41.177 に答える