cpeddie
cpeddie

Reputation: 799

js async/await not working

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

Upvotes: 0

Views: 7360

Answers (3)

user2400083
user2400083

Reputation: 51

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)
}

Upvotes: 0

Mark
Mark

Reputation: 92440

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>

Upvotes: 4

Geuis
Geuis

Reputation: 42267

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.

Upvotes: 2

Related Questions