For some reason my async call is not working as expected. Here's what I'm trying to do:
- Make several ajax calls in a loop
- On success, push some API data to a global array
- Use that array in another function (e.g print it out)
var authcodes = ["E06000001","E06000002","E06000003"];
var dict = [];
async function ajaxCall() {
for(var i=0;i<authcodes.length;i++){
$.ajax({
type: "GET",
url: 'https://api.coronavirus.data.gov.uk/v1/data?filters=areaCode=' + authcodes[i] +'&structure={"areaCode":"areaCode","cumCasesByPublishDate":"cumCasesByPublishDate"}',
dataType: "json",
success: function(data) {
dict.push(data.data[0].cumCasesByPublishDate);
}
});
} return dict;
}
async function printArr () {
const someApiRes = await ajaxCall()
console.log(someApiRes[1]); //this doesn't work
console.log(dict[1]); //this doesn't work
}
printArr();
Here is the JSFiddle with code commented: https://jsfiddle.net/gjv9hrpo/1/
I understand that the printArr() function has to be ran after the array is populated due to the async nature which I hoped the await would solve. Am I using it wrong?
Thanks.
awaiting on anything in side theajaxCallfetch()instead, it already returns promise, and GETting JSON is very straightforward to boot.await $.ajax({..should do it I believe!