js async/await not working

后端 未结 2 546
南旧
南旧 2021-01-27 05:44

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

2条回答
  •  时光说笑
    2021-01-27 05:53

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

提交回复
热议问题