Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  132] [ 6]  / answers: 1 / hits: 18127  / 11 Years ago, fri, july 26, 2013, 12:00:00
$(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.


More From » jquery

 Answers
14

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);
});

[#76725] Thursday, July 25, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ignacio

Total Points: 467
Total Questions: 128
Total Answers: 79

Location: Luxembourg
Member since Tue, Mar 14, 2023
1 Year ago
ignacio questions
;