I'm trying to wrap my head around async/await and how to use them. I'm following some examples I've seen to the letter (I think), but it the await is not actually waiting for ajax response. Here is the code:
async function doAjaxGet(ajaxurl) {
const result = await $.ajax({
url: ajaxurl,
type: 'GET',
datatype: "text",
});
return result;
}
$(document).ready(function () {
let json = doAjaxGet( "/static/imeiXref.json");
console.log('json: ', json);
processJSONData( json );
});
function processJSONData(data) {
console.log('Data: ', data);
Data = JSON.parse( data);
But the await keyword is not actually waiting for the result to be returned. In the console log I get the following:
json: Promise {<pending>}
Data: Promise {<pending>} controller.js:98
jQuery.Deferred exception: Unexpected token o in JSON at position 1 SyntaxError: Unexpected token o in JSON at position 1 jquery.min.js:2
at JSON.parse (<anonymous>)
at processJSONData (http://localhost:3000/js/controller.js:99:25)
at HTMLDocument.<anonymous> (http://localhost:3000/js/controller.js:80:5)
at l (http://localhost:3000/js/jquery.min.js:2:29375)
at c (http://localhost:3000/js/jquery.min.js:2:29677) undefined
jquery.min.js:2 Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at processJSONData (controller.js:99)
at HTMLDocument.<anonymous> (controller.js:80)
at l (jquery.min.js:2)
at c (jquery.min.js:2)
But if I actually look at the result that is returned in the console, the data is actually there. So it seems that await function is not 'awaiting' and my code continues to execute right after the ajax call, and it is trying to parse JSON data that has not been returned yet. How do I get the await to await?
Thanks.....
jsonis a promise, because that's what async functions return