上一篇介绍了promise的概念和方法
这一篇介绍如何使用promise实现ajax
- 用原生js实现ajax
getData(method, url, successFun, failFun){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open(method, url);
xmlHttp.send();
xmlHttp.onload = function () {
if (this.status == 200 ) {
successFun(this.response);
} else {
failFun(this.statusText);
}
};
xmlHttp.onerror = function () {
failFun(this.statusText);
};
- 用Promise对象实现ajax
const getJSON = function(url) {
const promise = new Promise(function(resolve, reject){
const handler = function() {
if (this.readyState !== 4) {
return;
}
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
const client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
});
return promise;
};
//调用
getJSON("/posts.json").then(function(json) {
console.log('Contents: ' + json);
}, function(error) {
console.error('出错了', error);
});
- 用Promise对象封装axios
function axios(url,params) ={
return new Promise((resovle,reject)=>{
axios.get(url,params).then(res=>{
resovle(res)
}).catch(err=>{
reject(err)
})
})
}
//调用
axios("/posts.json").then(function(json) {
console.log('Contents: ' + json);
}).catch(function(error) {
console.error('出错了', error);
});