加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

使用 async await 封装微信小程序HTTP请求

发布时间:2020-12-14 19:08:21 所属栏目:资源 来源:网络整理
导读:1. 编写将普通回调函数形式的方法转换为promise方法的promisic方法 1 // util.js 2 const promisic = function (func) { 3 return function (params = {}) { 4 new Promise((resolve,reject) = { 5 const args = Object.assign(params,{ 6 success: (res) =

1. 编写将普通回调函数形式的方法转换为promise方法的promisic方法

复制代码

 1 // util.js
 2 const promisic = function (func) {
 3     return function (params = {}) {
 4         new Promise((resolve,reject) => {
 5             const args = Object.assign(params,{
 6                 success: (res) => {
 7                     resolve(res)
 8                 }, 9                 fail: (error) => {
10                     reject(error)
11                 }
12             })
13             func(args)
14         })
15     }
16 }
17 
18 export {
19     promisic
20 }

复制代码

?

2. 编写Http类封装HTTP请求

,data }) { 11 将wx.request方法转换成promise方法 12 const res = await promisic(wx.request)({ 13 url: `${config.apiBaseUrl}${url}`,128); line-height: 1.5 !important;">14 method,128); line-height: 1.5 !important;">15 data,128); line-height: 1.5 !important;">16 header: { 17 appkey: config.appkey 18 } 19 }) 20 return res.data 21 } 22 23 } 24 25 export { 26 Http 27 }
3. 编写Theme业务类调用封装好的Http请求
,data: { names: 't-1' } }) } } export { Theme }
4. 在page中调用Theme业务类获取首页主题A方法
3 4 Page({ 5 6 data: { 7 topTheme: {} 8 },128); line-height: 1.5 !important;">10 async onLoad (options) { 11 获取首页主题A 12 const data = await Theme.getHomeLocationA() 13 this.setData({ 14 topTheme: data[0] 15 }) 16 } 18 })
附上目录结构

?

这样就可以愉快地使用async await形式的Http请求了,彻底摆脱各种callback方法!

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读