js async/await not working

后端 未结 2 547
南旧
南旧 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)
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    0 讨论(0)
  • 2021-01-27 06:10

    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.

    0 讨论(0)
提交回复
热议问题