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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?