且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Ajax和异步等待

更新时间:2022-03-23 09:34:11

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兑现承诺,但您不必:

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