George_Fal 2018-06-20 15:30 采纳率: 0%
浏览 158

Ajax和异步等待

I am a bit confused as to why my ajax call doesnt return a result. I thought a method defined as async automatically returns a promise. What am I doing wrong?

async AjaxCall(filePath) {
      let xhttp = new XMLHttpRequest();

      xhttp.open('POST', filePath, true);
      xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      xhttp.send();

     xhttp.onreadystatechange = function() {
          if (xhttp.readyState === 4 && xhttp.status === 200) {
            return xhttp.responseText;
          }
      }
  }


async function Test() {
  var result = await AjaxCall("file.php");
  alert(result);
}

Test();
  • 写回答

2条回答 默认 最新

  • weixin_33727510 2018-06-20 15:37
    关注

    async/await is (really useful) syntactic sugar for creating and consuming promises. Your AjaxCall function implicitly creates a promise, but then also implicitly resolves it immediately with the value undefined because you never await anything, and the only return isn't directly in AjaxCall but is instead in the onreadystatechange callback.

    You can wrap a promise around XHR, but you don't have to: fetch already does:

    async function Test() {
      var result = await fetch("file.php");
      if (result.ok) {
          alert(await result.text());
       }
    }
    

    But if you want to do it yourself, you'll need to explicitly create and consume a promise rather than using async on AjaxCall:

    function AjaxCall(filePath) {
        return new Promise((resolve, reject) => {
            let xhttp = new XMLHttpRequest();
    
            xhttp.open('POST', filePath, true);
            xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xhttp.send();
    
            xhttp.onreadystatechange = function() {
                if (xhttp.readyState === 4) {
                    if (xhttp.status === 200) {
                        resolve(xhttp.responseText);
                    } else {
                        reject(); // Probably including some rejection reason
                    }
                }
            };
        });
    }
    
    评论

报告相同问题?