I've read How do I return the response from an asynchronous call? and understand the nature of asynchronous calls in JavaScript.
Using jQuery 3.2.1, I have some code which makes an ajax call to an endpoint, /get-data
, which returns a JSON structure with a property and value, e.g.
{ "download_list_groups_limit" : 2 }
If the JSON response doesn't contain the property download_list_groups_limit
then I return a default value, 10
in this case (see code below).
This means that I either have the result of the ajax response (2
in this example) or a default value of 10.
I want to assign the result to a variable called download_list_groups_limit
.
I understand the async nature of JavaScript means that the ajax call to /get-data
has to complete before the result is available.
I have the following code:
var download_list_groups_limit = getSubstanceLimits(function(result) {
console.log('result = ' + result);
});
console.log('download_list_groups_limit = ' + download_list_groups_limit);
function getSubstanceLimits(callback) {
let filtered_response;
$.ajax({
url : '/get-data',
success: function(response) {
if (response.download_list_groups_limit) {
filtered_response = response.download_list_groups_limit; // 2 in this example
} else {
filtered_response = 10; // Default
}
callback(filtered_response);
}
});
}
The console.log
statements return the following:
download_list_groups_limit = undefined
result = 2
My question is about scope: If I want to use my result
in the global scope of my script (e.g. assign a variable and have it set to 2
) how can I do that? It seems the only place I can do that is inside the callback, i.e. inside getSubstanceLimits(function(result) { ... });
If I need to use the value, 2, outside the callback across various points in my script, how is that possible?