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方法!