Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  58] [ 3]  / answers: 1 / hits: 23486  / 10 Years ago, wed, august 27, 2014, 12:00:00

I have the following



function doAjax()
{
var result = false;
$.ajax(url, data)
.done(function(){
// Do a bunch
// of computation
// blah blah blah
result = true;
}).fail(function(){
result = false;
});
return result;
}

function doSomething()
{
if ( doAjax() == true )
console.log('success');
else
console.log('failed');
}

function doSomethingElse()
{
if ( doAjax() == true )
console.log('success');
else
console.log('failed');
}


I have a function that runs some ajax, then returns true or false, depending on whether the ajax was successful or not. This ajax function I call from multiple places in my code.



Because the function ends before the ajax finishes, it always returns false. How do I avoid this?



I have read something suggesting that I do a return $.ajax() in my function and then move the .done() and .fail() functions to my doSomething() and doSomethingElse() functions. However, in my .done() method, I do a BUNCH of computation. Lots of code. So the problem is, that if I move the .done() function to my other functions, I am duplicating a bunch of code.



How do I avoid this? Just wrap the computation into it's own function and call it wherever necessary?


More From » jquery

 Answers
39

Restructure your code to use callbacks instead of returns, like this...



function doAjax(callback)
{
$.ajax(url, data)
.done(function(){
// Do a bunch
// of computation
// blah blah blah
callback(true);
}).fail(function(){
callback(false);
});
}

function doSomething()
{
doAjax(function(result){
if (result == true )
console.log('success');
else
console.log('failed');
});
}

function doSomethingElse()
{
doAjax(function(result){
if (result == true )
console.log('success');
else
console.log('failed');
});
}

[#69644] Sunday, August 24, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hanna

Total Points: 66
Total Questions: 99
Total Answers: 101

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;