在下面的代码中,如果我在ajax函数的最开头插入行throw "Error";
,则catch捕获异常并调用dispatchError。但是,如果它在xhttp.onreadystatechange箭头函数中抛出,则不会捕获异常。为什么?
let ajax = (url, cb, data) => {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = () => {
if (xhttp.readyState == 4) {
let data;
if (xhttp.responseText) {
data = JSON.parse(xhttp.responseText);
}
cb({status: xhttp.status, data});
}
};
xhttp.open(data?"POST":"GET", url, true);
if (data) {
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send(JSON.stringify(data));
} else {
xhttp.send();
}
};
export const getData = () => {
return new Promise((resolve, reject) => {
ajax("url",response => response.status===200?
resolve(response.data):
reject(new Error("Error"))
);
});
getData()
.then(d=>dispatchData(d))
.catch(e=>dispatchError(e))