I have a function, which declares a variable, uses $.when to perform three ajax requests, modifies the variable inside the .done() method and returns the value:
someFunction = function(){
var myVar;
$.when(ajax1(), ajax2(), ajax3()).done(function(){
myvar = "something";
});
return myVar;
}
However, due to its asyncronous nature the return statement is executed first and returns undefined
.
I confirmed this by adding something before the return statement (for debugging purposes):
setTimeout(function(){
console.log(myVar);
}, 2000);
After waiting 2 seconds (long enough for all requests and callbacks to finish), it returned the proper value.
So, how should I write this properly in order to make it sync?