原生js封裝promise
阿新 • • 發佈:2019-01-01
原生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);
})