问题描述
我对为什么我的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和异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!