本文介绍了Ajax和异步等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对为什么我的ajax调用不返回结果感到有些困惑.我认为定义为异步的方法会自动返回promise.我在做什么错了?

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();

推荐答案

async/await是(确实有用的)语法糖,用于创建和使用Promise.您的AjaxCall函数隐式创建了一个promise,但同时也隐式地使用值undefined解析了它,因为您从不await进行任何操作,并且唯一的return不是直接在AjaxCall中而是在onreadystatechange回调.

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.

可以围绕XHR兑现承诺,但您不必: fetch 已经完成:

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

但是,如果您想自己做,则需要显式创建并使用一个Promise,而不是在AjaxCall上使用async:

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

这篇关于Ajax和异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:58