盒子
盒子

Promise封装原生ajax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const promiseAjax = function(url) {
return new Promise((resolve, reject) => {
const handler = function() {
if(this.readyState !== 4) {
return;
}
if(this.status === 200) {
return resolve(this.responseText);
} else {
return reject(new Error(this.statusText));
}
};
const client = new XMLHttpRequest();
client.open('GET', url);
client.onreadystatechange = handler;
client.responeType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
});
}

promiseAjax('cust/UserController/getUserList.do')
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})

总结:promise还是用了回调,只是好看一点

支持一下
扫一扫,支持 Alin
  • 微信扫一扫
  • 支付宝扫一扫