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

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
                    }
                }
            };
        });
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog