async/await结合promise可以进一步简化,省去.then(),使函数类似同步的方式执行
//微信小程序wx-request结合promise还有async await进行封装
var reqTime = 0; //记录请求次数
const request = (params) => {
reqTime++;
//加载弹框
wx.showLoading({
title: '加载中...',
mask: true
});
//返回
return new Promise((resolve, reject) => {
wx.request({
//解构params获取请求参数
...params,
success: (result) => {
resolve(result);
},
fail: (err) => {
reject(err);
},
complete: () => {
reqTime--;
//停止加载
if (!reqTime)
wx.hideLoading();
}
});
});
}
//普通调用方式
function getSwiper1() {
request({
url: "https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata"
}).then(res => {
console.log(res);
});
}
//async await
async function getSwiper2() {
const res = await request({
url: "https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata"
});
console.log(res);
}