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?