各种回调会造成回调地狱的问题,回调函数一层套着一层,代码难以阅读,后期难以维护的问题
解决办法:使用regenerator-runtime
regenerator-runtime是facebook的regenerator模块
生成器函数、async、await函数经babel编译后,regenerator-runtime模块用于提供功能实现。
引入facebook/regenerator 中的packages/regenerator-runtime/runtime.js
步骤1 引入并注册因全局都要用到,所有在app.js中引入,并注册全局对象中.
app.js
import regeneratorruntime from './lib/runtime'app({ ... regeneratorruntime, onlaunch(){}, onshow() {}, onhide() {}, ...})
步骤2 封装requestrequest.js
const method = { get: 'get', post: 'post', put: 'put', delete: 'delete'}let baseurl = ''const interceptors = []class request { /** * response interceptor */ intercept(res, resolve, reject) { return interceptors .filter((f) => typeof f === 'function') .every((f) => f(res, resolve, reject)) } /** * request */ request(option) { const header = { 'content-type': 'application/x-www-form-urlencoded' } const { url, method, data = {} } = option return new promise((resolve, reject) => { try { wx.request({ url: baseurl + url, method: method || method.get, data, header, success: (res) => this.intercept(res, resolve, reject), fail: (err) => { if ( err && err.errmsg && err.errmsg.indexof('request:fail') !== -1 ) { console.error('wx request error: ', err) } else { wx.showtoast({ title: json.stringify(err), icon: 'none', duration: 10000 }) } } }) } catch (err) { wx.showtoast({ title: err.message, icon: 'none' }) } }) } get(url, data) { return this.request({ url, method: method.get, data }) } post(url, data) { return this.request({ url, method: method.post, data }) } put(url, data) { return this.request({ url, method: method.put, data }) } delete(url, data) { return this.request({ url, method: method.delete, data }) } all(tasks) { return promise.all(tasks) }}/** * 设置base url */function setbaseurl(url) { baseurl = url}/** * 默认response拦截器 */function adddefaultinterceptor() { interceptors.push((res, resolve, reject) => { const status = res.statuscode if (status !== 200) { return reject(new error(`internet error: ${status}`)) } const body = res.data if (body.errno !== 0) { return reject({ message: body.error, body }) } return resolve(body.data) })}const request = new request()export { setbaseurl, adddefaultinterceptor, request }
步骤3 使用async await如:
import { request, setbaseurl, adddefaultinterceptor } from './lib/request'adddefaultinterceptor()app({ ... async onlaunch() { const userinfo = await request.get('/user/info') console.log(userinfo) } ...})
小程序原生api使用async await不用再写各种success、fail等回调了,代码清晰很多,易读性更强.
步骤1 封装原生api用promise化wxp.js
/** * promise微信api方法 */function wxpromise(api) { function func(options, ...params) { return new promise((resolve, reject) => { api( object.assign({}, options, { success: (res) => { resolve(res) }, fail: reject }), ...params ) }) } return func}export default { // 界面交互 showtoast: wxpromise(wx.showtoast), showloading: wxpromise(wx.showloading), showmodal: wxpromise(wx.showmodal), showactionsheet: wxpromise(wx.showactionsheet), // 导航条 setnavigationbartitle: wxpromise(wx.setnavigationbartitle), setnavigationbarcolor: wxpromise(wx.setnavigationbarcolor), settopbartext: wxpromise(wx.settopbartext), // 导航 navigateto: wxpromise(wx.navigateto), redirectto: wxpromise(wx.redirectto), switchtab: wxpromise(wx.switchtab), relaunch: wxpromise(wx.relaunch), // 用户相关 login: wxpromise(wx.login), checksession: wxpromise(wx.checksession), authorize: wxpromise(wx.authorize), getuserinfo: wxpromise(wx.getuserinfo), // 支付 requestpayment: wxpromise(wx.requestpayment), // 图片 chooseimage: wxpromise(wx.chooseimage), previewimage: wxpromise(wx.previewimage), getimageinfo: wxpromise(wx.getimageinfo), saveimagetophotosalbum: wxpromise(wx.saveimagetophotosalbum), // 文件 uploadfile: wxpromise(wx.uploadfile), downloadfile: wxpromise(wx.downloadfile), // 录音 startrecord: wxpromise(wx.startrecord), // 音频播放 playvoice: wxpromise(wx.playvoice), // 音乐播放 getbackgroundaudioplayerstate: wxpromise(wx.getbackgroundaudioplayerstate), playbackgroundaudio: wxpromise(wx.playbackgroundaudio), seekbackgroundaudio: wxpromise(wx.seekbackgroundaudio), // 视频 choosevideo: wxpromise(wx.choosevideo), savevideotophotosalbum: wxpromise(wx.savevideotophotosalbum), // 文件 savefile: wxpromise(wx.savefile), getfileinfo: wxpromise(wx.getfileinfo), getsavedfilelist: wxpromise(wx.getsavedfilelist), getsavedfileinfo: wxpromise(wx.getsavedfileinfo), removesavedfile: wxpromise(wx.removesavedfile), opendocument: wxpromise(wx.opendocument), // 数据缓存 setstorage: wxpromise(wx.setstorage), getstorage: wxpromise(wx.getstorage), getstorageinfo: wxpromise(wx.getstorageinfo), removestorage: wxpromise(wx.removestorage), // 位置 getlocation: wxpromise(wx.getlocation), chooselocation: wxpromise(wx.chooselocation), openlocation: wxpromise(wx.openlocation), // 设备 getsysteminfo: wxpromise(wx.getsysteminfo), getnetworktype: wxpromise(wx.getnetworktype), startaccelerometer: wxpromise(wx.startaccelerometer), stopaccelerometer: wxpromise(wx.stopaccelerometer), startcompass: wxpromise(wx.startcompass), stopcompass: wxpromise(wx.stopcompass), // 打电话 makephonecall: wxpromise(wx.makephonecall), // 扫码 scancode: wxpromise(wx.scancode), // 剪切板 setclipboarddata: wxpromise(wx.setclipboarddata), getclipboarddata: wxpromise(wx.getclipboarddata), // 蓝牙 openbluetoothadapter: wxpromise(wx.openbluetoothadapter), closebluetoothadapter: wxpromise(wx.closebluetoothadapter), getbluetoothadapterstate: wxpromise(wx.getbluetoothadapterstate), startbluetoothdevicesdiscovery: wxpromise(wx.startbluetoothdevicesdiscovery), stopbluetoothdevicesdiscovery: wxpromise(wx.stopbluetoothdevicesdiscovery), getbluetoothdevices: wxpromise(wx.getbluetoothdevices), getconnectedbluetoothdevices: wxpromise(wx.getconnectedbluetoothdevices), createbleconnection: wxpromise(wx.createbleconnection), closebleconnection: wxpromise(wx.closebleconnection), getbledeviceservices: wxpromise(wx.getbledeviceservices), // ibeacon startbeacondiscovery: wxpromise(wx.startbeacondiscovery), stopbeacondiscovery: wxpromise(wx.stopbeacondiscovery), getbeacons: wxpromise(wx.getbeacons), // 屏幕亮度 setscreenbrightness: wxpromise(wx.setscreenbrightness), getscreenbrightness: wxpromise(wx.getscreenbrightness), setkeepscreenon: wxpromise(wx.setkeepscreenon), // 振动 vibratelong: wxpromise(wx.vibratelong), vibrateshort: wxpromise(wx.vibrateshort), // 联系人 addphonecontact: wxpromise(wx.addphonecontact), // nfc gethcestate: wxpromise(wx.gethcestate), starthce: wxpromise(wx.starthce), stophce: wxpromise(wx.stophce), sendhcemessage: wxpromise(wx.sendhcemessage), // wi-fi startwifi: wxpromise(wx.startwifi), stopwifi: wxpromise(wx.stopwifi), connectwifi: wxpromise(wx.connectwifi), getwifilist: wxpromise(wx.getwifilist), setwifilist: wxpromise(wx.setwifilist), getconnectedwifi: wxpromise(wx.getconnectedwifi), // 第三方平台 getextconfig: wxpromise(wx.getextconfig), // 转发 showsharemenu: wxpromise(wx.showsharemenu), hidesharemenu: wxpromise(wx.hidesharemenu), updatesharemenu: wxpromise(wx.updatesharemenu), getshareinfo: wxpromise(wx.getshareinfo), // 收货地址 chooseaddress: wxpromise(wx.chooseaddress), // 卡券 addcard: wxpromise(wx.addcard), opencard: wxpromise(wx.opencard), // 设置 opensetting: wxpromise(wx.opensetting), getsetting: wxpromise(wx.getsetting), // 微信运动 getwerundata: wxpromise(wx.getwerundata), // 打开小程序 navigatetominiprogram: wxpromise(wx.navigatetominiprogram), navigatebackminiprogram: wxpromise(wx.navigatebackminiprogram), // 获取发票抬头 chooseinvoicetitle: wxpromise(wx.chooseinvoicetitle), // 生物认证 checkissupportsoterauthentication: wxpromise(wx.checkissupportsoterauthentication), startsoterauthentication: wxpromise(wx.startsoterauthentication), checkissoterenrolledindevice: wxpromise(wx.checkissoterenrolledindevice)}
以上为小程序基本的api整理,贴出来供大家使用~
步骤2 使用import wxp from './lib/wxp'app({ ... wxp, async onlaunch() { const res = await wxp.getsysteminfo() console.log(res) } ...})
相关学习推荐:小程序开发教程
以上就是怎么使微信小程序支持async await?的详细内容。