使用Promise,避免回调金字塔
也可以封装一个Promise类
/* 请求封装 */
const apiAgree = "https"; // 全局默认协议
const apiHttpHost = "www.xxx.com";
const apiHttpsHost = "www.xxx.com";
function f(url,method,data,headers,agree){
let apiHost = agree == "https"?apiHttpsHost:apiHttpHost;
let apiUrl = agree + "://" + apiHost + url;
data = data || {};
let header = headers || {};
let sessionId = wx.getStorageSync("UserSessionId"); // 获取缓存会话
if (!header || !header["SESSIONID"]) {
header["SESSIONID"] = sessionId;
}
console.log("==================REQUEST BEGIN====================");
console.log("agree:", agree);
console.log("apiHost:", apiHost);
console.log("apiUrl:", apiUrl);
console.log("method:", method);
console.log("data:", data);
console.log("header:", header);
console.log("==================REQUEST END====================");
wx.showNavigationBarLoading();
let promise = new Promise(function(resolve,reject){
wx.request({
url: apiUrl,
method:method,
header:header,
data:data,
success:function(res){
if(typeof res.data === "object"){
if(res.data.status){
if (res.data.status === -200) {
// 需要重新登录
wx.showToast({
title: res.data.msg,
icon: "none"
});
reject("请重新登录");
} else if (res.data.status === -1) {
// 普通的请求错误
reject("请求错误");
}
}
}
resolve(res);
},
fail:reject("error"),
complete: function () { wx.hideNavigationBarLoading();}
})
})
return promise;
}
// 导出模块
module.exports = {
"get":function(url, data, header, agree = apiAgree){
return f(url,"GET", data ,header , agree);
},
"post": function (url, data, header, agree = apiAgree) {
return f(url, "POST", data, header, agree);
}
};