Currently, I am attempting to handle a getJson
call and process the data received. Despite trying various solutions such as using $.ajax
's async: false
(which did not work due to the query being cross domain), callbacks, and the .done
portion of a basic $.ajax
call, I have now turned to async-await. Below is an excerpt from my code:
var ths = getTrailheads(turl);
console.log("trailheads promise");
console.log(ths);
ths.then(function(data) {
addTrailheadsToMap(data);
});
async function getTrailheads(turl) {
var result = await $.ajax({
url: turl,
datatype: 'json'
});
return result;
}
Although it occasionally works when the AJAX call returns quickly enough, most of the time the console log displays:
https://i.sstatic.net/O5iA3.png
This screenshot portrays the promise with status
marked as Resolved
. The promise object exists, yet the status indicates Processing
.
Despite this being a common issue, the typical solutions do not seem to be effective in my case. Any guidance would be greatly appreciated.
Update:
preGetTrailheads(turl);
}
async function preGetTrailheads(turl) {
var ths = await getTrailheads(turl);
console.log("trailheads promise");
console.log(ths);
addTrailheadsToMap(ths);
}
async function getTrailheads(turl) {
var result = await $.ajax({
url: turl,
datatype: 'json'
});
return result;
}
Now, instead of receiving a promise, I obtain the object directly; however, the object remains in a "Processing" state and fails upon usage. object dump
Update 2: I acknowledge that both of your approaches are correct, and that's the standard procedure. You can find my codepen here. It tends to function well, except for the initial run where it fails (also, successful output goes to the browser log). I need to investigate why this occurs in my application. Interestingly, reloading the page seems to make it work for a particular dataset.