promise 封装 axios
/*axios({
method:"get",
url:"./data.json",
data:{
id:10
}
}).then((res)=>{
console.log(res)
},(e)=>{
console.log(e);
})*/
function axios(options) {
let promise = new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
var data = "";
//数据处理
for (var key in options.data) {
data += "&" + key + "=" + options.data[key]
}
if (options.method == "get") {
let url = options.url + "?" + data.slice(1);
xhr.open(options.method, url);
xhr.send();
} else if (options.method == "post") {
xhr.open(options.method, options.url);
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send(data);
}
xhr.onreadystatechange = function () {
let timer = null;
let timeout = options.timeout?options.timeout:5000
if(xhr.readyState == 4 && xhr.status == 200){
let res = JSON.parse(xhr.responseText);
clearTimeout(timer);
resolve(res);
}
timer = setTimeout(()=>{
clearTimeout(timer);
reject(xhr.status);
},timeout)
}
})
return promise;
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步