原生js封装promise
1.代码如下:
function getJson(type,url,data){
const promise=new Promise(function(resolve, reject){
const handle=function(){
if(this.readyState!=4){
return;
}
if(this.status==200){
resolve(this.response);//请求成功,抛出接收到的信息
}else{
reject(new Error(this.statusText));//请求失败,打印出请求错误信息
}
}
const xml=new XMLHttpRequest();//创建xml对象,用于发送请求
xml.open(type,url);//设置发送请求的类型,和地址
xml.responseType='json';//设置请求数据的类型
xml.onreadystatechange=handle;
if(type=='get'){
xml.send();
}else{
xml.setRequestHeader("Content-Type", "application/json");//设置post请求头
xml.send(JSON.stringify(data));//data序列化
}
})
return promise;
}
2.使用格式:
getJson('get','http://localhost:2222/getData')
.then(res=>{ //请求成功获取到数据
console.log(res);
},err=>{ //请求失败打印出错误
console.log(err.message);
})