如何让微信小程序支持异步await?

本站:VPS参考评测推荐,专注分享VPS服务器优惠信息!若您是商家也可以在本站进行投稿,查看详情!此外我们还提供软文收录、PayPal代付、广告赞助等服务,查看详情!
部分文章发布时间较久远,可能存在未知因素,购买时建议在本站搜索商家名称,可查看相关文章充分了解商家!若非中文页面可使用谷歌浏览器同步翻译!PayPal代付/收录合作

微信小程序用的是异步await微信小程序,不支持异步。写代码太难受了。各种回调都会造成回调地狱的问题。回调函数一个个嵌套,代码难读,后期维护也很难。

解决方法:使用regenerator -运行时。

Regenerator-runtime是facebook的再生器模块的生成器函数。babel编译async和await函数后,使用regenerator -运行时模块提供功能实现。

在facebook/regenerator中引入packages/regenerator -runtime/runtime . js

步骤1简介并注册,因为它是全球通用的。都是在app.js中引入,在全局对象中注册的。

app.js

从 # 39;。/lib/runtime # 39;应用程序({...再生器运行时,OnLaunch () {},OnShow () {},OnHide () {},...})步骤2封装requestrequest.js

const METHOD = { GET: # 39;获取 # 39;,帖子: # 39;邮政 # 39;,放: # 39;放 # 39;,删除: # 39;删除 # 39;} let baseUrl = # 39'const interceptors =[]类请求{ /** *响应拦截器*/ intercept(res,resolve,reject) {返回拦截器。过滤器((f)= gt;typeof f = = = # 39功能 # 39;) .every((f)= gt;f(res,resolve,reject))}/* * * request */request(option){ const header = { # 39;内容-类型 # 39;: 'application/x-www-form -urlencoded # 39;} const { url,method,data = { } } = option return new Promise((resolve,reject)= gt;{ try { wx . request({ URL:base URL+URL,method: method || METHOD。GET,data,header,success:(RES)= gt;this.intercept(res,resolve,reject),fail:(err)= gt;{如果(错误 错误消息 err . errmsg . index of( # 39;请求:失败 # 39;) != = -1){ console . error( # 39;wx请求错误: # 39;,err)} else { wx . show toast({ title:JSON . stringify(err),icon: # 39;无 # 39;,持续时间:10000 })} } })} catch(err){ wx . show toast({ title:err . message,icon: # 39;无 # 39;}) } }) } 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)} }/* * Set base URL */function Set base URL(URL){ base URL = URL }/* * *默认响应拦截器*/function addDefaultInterceptor(){ interceptors . push((RES,resolve,reject))= >;{ const status = RES . status code 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 { setbase URL,adddefaultinterceptor,request}步骤3使用async await如下:

从 # 39;导入{ request,setBaseUrl,addDefaultInterceptor }。/lib/request # 39;addDefaultInterceptor()应用程序({...async on launch(){ const userInfo = await request . get( # 39;/user/info # 39;)console.log(userInfo)}...})小程序原生api使用的是异步await,所以不需要写成功和失败等各种回调。代码更加清晰易读。

步骤1封装原生api,将wxp.js转化为Promise

/** * promise微信API方法*/函数wx promise(API){ function func(options,...params){ return new promise((resolve,reject)= >;{ api( Object.assign({},options,{ success:(RES)= gt;{ resolve(res) },fail: reject })。...params)}} return func}导出默认{//界面交互show toast:wx promise(wx . show toast)、show loading:wx promise(wx . show loading)、show modal:wx promise(wx . show action sheet)、//导航栏setnavigationbartitle:wx promise(wx . setnavigationbartitle)、setnavigationbarcolor:wx promise(wx . setnavigationbarcolor)、Settopbartext: wxPromise( download file:wx promise(wx . download file),//录音start record:wx promise(wx . start record),//音频播放play voice:wx promise(wx . GetBackgroundAudioPlayState),//音乐播放getbackgroundaudio:wx promise(wx . PlayBackgroundAudio),Seekbackgroundaudio:wx promise(wx . Seekbackgroundaudio),//视频选择视频:wx promise (wx.choose video),Savevideophotoalbum Start accelerator:wx promise(wx . Start accelerator)、stop accelerator:wx promise(wx . stop accelerator)、Start compass:wx promise(wx . stop compass)、//Call make phone Call:wx promise(wx . make phone Call)、//scan code:wx promise(wx . scancode)、//Clipboard data:wx promise(wx . setclipboard data)、getclipboard data:wx promise(wx . getclipboard data)、//蓝牙 //Contact AddPhoneContact:wx Promise(wx . AddPhoneContact),//NFC GethEstate:wx Promise(wx . GethEstate),start hce:wx Promise(wx . stop hce),sendHCEMessage:wx Promise(wx . sendHCEMessage),//Wi-Fi start wifi:wx Promise(wx . start wifi),stopWifi: wxPromise(wx.stopWifi), ChooseInvoiceTitle)、//生物认证checkissupportsoterauthentication:wx promise(wx . checkissupportsoterauthentication)、Startsoterauthentication:wx promise(wx . Startsoterauthentication)、checkissuerenrerolledinevice:wx promise(wx . checkissuerenrerolledinevice)}以上是小程序的基本api整理,贴出来供大家使用~

步骤2使用导入wxp从 # 39;。/lib/wxp # 39;应用程序({...wxp,async on launch(){ constres = awaitwx p . getsystem info()console . log(RES)}...})相关学习推荐:小程序开发教程以上就是如何让微信小程序支持async await?更多详情请关注本站其他相关文章!

本文由本站刊发,转载请注明:如何让微信小程序支持异步await? https://本站.com/77182.html

推荐站内搜索:虚拟主机香港主机备案空间、域名空间代理、免费域名空间申请、动态ip的vps、移动服务器托管、网站备案域名查询、独立ip主机、google永久免费的服务器、域名解析ip地址查询、