jQuery supports this out of the box, set the option async
to false
and the function call will be synchronous, instead of asynchronous.
Though I'd recommend you to keep the request async, see the "recommended solution" at the end of this post.
async (Boolean) Default: true
By default, all requests are sent asynchronously (i.e. this is set to
true by default). If you need synchronous requests, set this option to
false. Cross-domain requests and dataType: "jsonp" requests do not
support synchronous operation.
Note that synchronous requests may
temporarily lock the browser, disabling any actions while the request
is active.
But I'm using $.get
, that seems to be specific for $.ajax
?
Yes, but under the hood they are exactly the same thing.
jQuery.get ():
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
Sample implementation
aft.getToken = function (url) {
var theToken;
$.ajax({
url: url,
dataType: 'html'
success: function (data) {
theToken = $(data).find('input[name=__RequestVerificationToken]').val();
},
dataType: dataType
});
return theToken;
}
Recommended solution
As stated by the previously mentioned comment from the jQuery documentation asynchronous requests are normally NOT recommended, and will most often to more harm than good.
Instead you should try to implement the functionality asked for by using a callback or similar.
A callback is a function passed to some other function to handle a certain event, such as the success of your data retrieval. Just as you are passing a callback to $.get
in your own snippet.
Make your function aft.getToken
accept a second parameter named callback
which should be a function reference. Then call this function with the token replied by your ajax request as a parameter when data retrieval and "parsing" is finished.
aft.getToken = function (url, callback) {
var dst_object = this;
$.get (url, function (data) {
dst_object.stored_token = $(data).find (
'input[name=__RequestVerificationToken]'
).val ();
callback (dst_object.stored_token);
}, "html");
};
...
aft.getToken ('/path/to/file.html', function (token) {
console.log ("Got token: " + token);
});
...
console.log (aft.stored_token);