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

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

 1 // util.js
 2 const promisic = function (func) {
 3     return function (params = {}) {
 4         return 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请求

 1 // http.js
 2 import { promisic } from "./util"
 3 import { config } from "../config/config"
 4 
 5 /**
 6  * 使用 async await 封装HTTP请求
 7  */
 8 class Http {
 9 
10     static async request({ url, method='GET', data }) {
11         // 将wx.request方法转换成promise方法
12         const res = await promisic(wx.request)({
13             url: `${config.apiBaseUrl}${url}`,
14             method,
15             data,
16             header: {
17                 appkey: config.appkey
18             }
19         })
20         return res.data
21     }
22 
23 }
24 
25 export {
26     Http
27 }

 

3. 编写Theme业务类调用封装好的Http请求

// theme.js
import { Http } from "../utils/http"

/**
 * 编写主题请求业务类
 */
class Theme {

    /**
     * 获取首页主题A
     */
    static async getHomeLocationA() {
        return await Http.request({
            url: 'xx/xx/xxx',
            data: {
                names: 't-1'
            }
        })
    }

}

export {
    Theme
}

 

4. 在page中调用Theme业务类获取首页主题A方法

 1 // home.js
 2 import { Theme } from '../../model/theme'
 3 
 4 Page({
 5 
 6   data: {
 7     topTheme: {}
 8   },
 9 
10   async onLoad (options) {
11     // 获取首页主题A
12     const data = await Theme.getHomeLocationA()
13     this.setData({
14         topTheme: data[0]
15     })
16   }
17 
18 })

 

附上目录结构

 

 

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

 

posted on 2019-10-07 17:43  动物管理猿  阅读(1672)  评论(0编辑  收藏  举报

导航