0

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.....

2
  • so .. json is a promise, because that's what async functions return Commented Mar 1, 2018 at 1:56
  • Setup a codepen.io demo Commented Mar 1, 2018 at 2:16

3 Answers 3

4

async functions return promises. Even when you return something from the async function, it's only going to be the value the promise resolves to.

You need to do something like this to use the promise:

$(document).ready(function () {
    doAjaxGet( "/static/imeiXref.json")
    .then(json => {
       console.log('json: ', json);
       processJSONData( json );
    })
});

EDIT. Here's a working snippet. Note, however that this is downloading json not a string, so there is no need to parse it. That's really a different question than the async issue, which seems to be working okay.

async function doAjaxGet(ajaxurl) {
  const result = await $.ajax({
    url: ajaxurl,
    type: 'GET',
  });
  return result;
}

$(document).ready(function() {
  doAjaxGet("https://jsonplaceholder.typicode.com/posts/1")
    .then(json => {
      console.log('json: ', json);
      processJSONData(json);

    })
});


function processJSONData(data) {
  // NOTE: data is already parsed
  console.log('Data: ', data);
  console.log("id: ", data.userId)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

4 Comments

... and you can easily add a catch clause in this promise chain.
This doesn't work either. This seems to add really strange behavior. The console.log('Data: ', data); displays the actual data on the console log. But the next line that calls JSON.parse is still getting an empty record.
@cpeddie you should check the content-type being returned from the server. It sounds like you are trying to parse already parsed json. This could be because you are using datatype: "text" instead of dataType: "text"`. I'll add an edit that shows a working example.
The datatype: "text" was the issue. As soon as I changed it to dataType everything is working. Arg. What a simple thing had me pulling my hair out. Thank you for your help!!!
2

So here:

$(document).ready(function () {
    let json = doAjaxGet( "/static/imeiXref.json");
    console.log('json: ', json);
    processJSONData( json );
});

You're not telling let json to wait for the response from doAjaxGet. Its awaiting inside the doAjaxGet function but everything else is executing sequentially without waiting.

What you want to do is this (I think):

$(document).ready(async function () {
    let json = await doAjaxGet( "/static/imeiXref.json");
    console.log('json: ', json);
    processJSONData( json );
});

Async/await is basically syntactic sugar around promises. await waits for a promise to resolve, so you have to do async/await at every level you're using the promise chain, or you can just use standard promise.then() style coding.

4 Comments

await returns a promise - no, await waits for the promise to resolve\
Can you actually get an async function to run in jQuery's .ready()? I can't get it to fire.
Trying to push async function usage up a level into document ready processing makes it really hard to add an error handler to prevent uncaught promise rejection errors.
Still not working. Now in the console log it doesn't tell me that the json and Data variables are promises and pending, I see the 27 entries that should be there from the file. But it is still getting to processJSON data too earlier and complaining about a 'o' at the beginning of the JSON record.
0

I see that this was posted long time ago but i was recently suffering from the same issue. I hope this helps for those who still needs help just like i needed.

// make sure that the function you are waiting for has no async/await keys but wrapped with promise
function doAjaxGet(ajaxurl) {
return Promise((resolve,reject)=>{
   $.ajax({
    url: ajaxurl,
    type: 'GET',
    success: function(result){
      resolve(result);
    },
    error:function(){
     reject('');
    }
  });
 }
}
// then in the function you wait the results, use async/await
$(document).ready(async function() {
  await doAjaxGet("https://jsonplaceholder.typicode.com/posts/1")
    .then(json => {
      console.log('json: ', json);
      processJSONData(json);

    })
});


function processJSONData(data) {
  // NOTE: data is already parsed
  console.log('Data: ', data);
  console.log("id: ", data.userId)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.