1、封装 $.ajax
/**
* 封装 $.ajax请求
* @param {Object} type GET|POST
* @param {Object} url
* @param {Object} data
*/
function request(type, url, data) {
return new Promise((resolve, reject) => {
$.ajax({
type: type,
url: httpUrl + url,
data: data,
dataType: "json",
headers: {
Authorization: 'Bearer ' + ConfigInfo.TOKEN
},
success: function(res) {
// console.log(JSON.stringify(res));
resolve(res)
},
error: function(err) {
// console.log(JSON.stringify(err));
reject(JSON.parse(err.responseText));
}
});
})
}
2、使用async 和await将异步操作变为同步操作,等待$.ajax请求的结果。
async getContent(){
try {
let res = await request("POST", "/api/XXX/XXXX", data);
console.log(res);
//do something
} catch (err) {
console.log(err.Message || "未知错误");
}
}