Here is a javascript function:
function getValue(key) {
var value;
switch(_options.myType){
case "cookie":
value = readFromCookie(key);
break;
case "localStorage":
value = readFromLocalStorage(key);
break;
case "db":
//return value from the server
// how do I wait for the result?
$.ajax({
type: "GET",
url: "123",
data: { .... },
success: function(data){
value = data;
}
});
break;
}
return value;
};
In case of sending ajax request, I need to wait untill the ajax request has been completed. How can I do it?
Not that I can't leave the function without having the value calculated. Which means that I can't place a function inside success:
handler which will return the value later (or perhaps I don't understand something?). So it must be calculated within the function getValue()
.
UPDATE
P.S. So how do refactor my code to be able to use callback inside success:
handler? Here is the second part of the code:
MyClass123.prototype.myMethod = function(value) {
//..............
var var1 = this.getValue("key1");
if (var1 == "123") { ... }
else { .... }
//..............
}
};