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 { .... }
//..............
}
};
See follow-up below
You could make the ajax request synchronous, but that’s generally a bad idea (and jQuery won’t support it much longer).
Instead, make
getValueaccept a callback:Note that I’m using
setTimeoutfor thereadFromCookieandreadFromLocalStoragecallbacks. Why? Because ifgetValuemight return its value asynchronously, it should always do so. using a timeout of0asks the browser to do it as soon as possible once control yields back to the browser (although it’s usually clamped to no less than 5-10ms).Re your comment below:
I missed that bit, but with all due respect, you can. It may require some refactoring of code, but you can do it, and should. This is how modern web applications work. If your structure doesn’t support it, you need to fix the structure. You can use
async: falseon the request as a temporary workaround until you can do it properly. (Hey, we’ve all been there and had to do things like that.) Note that it’s scheduled for retirement before too long (just jQuery’s support of it, you’ll still be able to use XHR directly to do synchronous requests).Re your updated question, here’s how you update that code:
Note how little it actually changes. The logic that used to follow the call to
getStateinstead goes into the callback you pass into it.