I am trying to save the results of a Socrata Query Language or SoQL query into a variable that I can use elsewhere. I think I understand that because of the async nature of ajax, I can't count on the value being available outside of the $.ajax().done() block, but I can't understand how to get the value out of the block.
let gasAve;
let settings = {
"async": true,
"crossDomain": true,
"url": "https://data.colorado.gov/resource/xyh2-p9cg.json?%24select=avg(allgradesgasprice)&%24where=date%20between%20'2017-01-01T12%3A00%3A00'%20and%20'2017-12-31T11%3A59%3A59'",
"method": "GET",
}
$.ajax(settings).done(function (response) {
console.log(response); // logs [Object {avg_allgradesgasprice="2.4292307692307692"}]
let [{"avg_allgradesgasprice":gasAve}] = response; // destructure the object
console.log(gasAve); // Within the block, I get the value 2.429....
});
console.log(gasAve); // Outside of the block I get undefined.
Couple gotachas here.
First is with the destructuring you're attempting. Within the scope of the anonymous function where you are processing the response, the let
redeclares gasAve
. This is separate from the original declaration, and the value thus was never assigned to your first declaration of gasAve
. Getting rid if the let
in your destructure operation will assign the value correctly within the scope you are expecting.
Second, the function that processes your response is executing asynchronously i.e. after the ajax call is made and the response is received. The console.log
outside the anonymous declaration executes before the value is assigned chronologically. The easy way to avoid this problem is to do all your work within the context of a the response processing function or from a function that is called from it. Something like this:
let gasAve;
let settings = {
"async": true,
"crossDomain": true,
"url": "https://data.colorado.gov/resource/xyh2-p9cg.json?%24%24app_token=gNqVzSHJ7pWovzVu8pRHdiMHe&%24select=avg(allgradesgasprice)&%24where=date%20between%20'2017-01-01T12%3A00%3A00'%20and%20'2017-12-31T11%3A59%3A59'",
"method": "GET",
}
$.ajax(settings).done(function (response) {
console.log(response); // logs [Object {avg_allgradesgasprice="2.4292307692307692"}]
[{"avg_allgradesgasprice":gasAve}] = response; // destructure the object
console.log(gasAve); // Within the block, I get the value 2.429....
displayStuff();
});
function displayStuff() {
console.log(gasAve)
}