更新时间: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.
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
}
}
};
});
}