In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article shows you how to make WeChat Mini Programs support async await. The content is concise and easy to understand. It will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
WeChat Mini Programs uses async await
All kinds of callbacks will cause the problem of callback hell, the callback function is sheathed layer by layer, the code is difficult to read and difficult to maintain later.
Solution:
Use regenerator-runtime
Regenerator-runtime is the regenerator module of facebook
Introducing packages/regenerator-runtime/runtime.js into facebook/regenerator
Step 1 introduce and register
Because the global is used, all are introduced in app.js and registered in the global object.
App.js
Import regeneratorRuntime from'. / lib/runtime'App ({. RegeneratorRuntime, onLaunch () {}, onShow () {}, onHide () {},...}) step 2 encapsulate request
Request.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)}} / * set base URL * / function setBaseUrl (url) {baseUrl = url} / * default response interceptor * / function addDefaultInterceptor () {interceptors.push ((res, resolve) Reject) = > {const status = res.statusCode if (status! = = 200) {return reject (new Error (`message: ${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} step 3 use async await
Such as:
Import {request, setBaseUrl, addDefaultInterceptor} from'. / lib/request'addDefaultInterceptor () App ({... Async onLaunch () {const userInfo = await request.get ('/ user/info') console.log (userInfo)}...}) Mini Program native api uses async await
Do not have to write a variety of success, fail and other callbacks, the code is much clearer, more readable.
Step 1 encapsulating native api for commitment
Wxp.js
/ * promise Wechat API method * / 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 {/ / interface interaction showToast: wxPromise (wx.showToast), showLoading: wxPromise (wx.showLoading), showModal: wxPromise (wx.showModal), showActionSheet: wxPromise (wx.showActionSheet), / / navigation bar setNavigationBarTitle: wxPromise (wx.setNavigationBarTitle) SetNavigationBarColor: wxPromise (wx.setNavigationBarColor), setTopBarText: wxPromise (wx.setTopBarText), / / Navigation navigateTo: wxPromise (wx.navigateTo), redirectTo: wxPromise (wx.redirectTo), switchTab: wxPromise (wx.switchTab), reLaunch: wxPromise (wx.reLaunch), / / user related login: wxPromise (wx.login), checkSession: wxPromise (wx.checkSession), authorize: wxPromise (wx.authorize), getUserInfo: wxPromise (wx.getUserInfo) / / pay requestPayment: wxPromise (wx.requestPayment), / / Picture chooseImage: wxPromise (wx.chooseImage), previewImage: wxPromise (wx.previewImage), getImageInfo: wxPromise (wx.getImageInfo), saveImageToPhotosAlbum: wxPromise (wx.saveImageToPhotosAlbum), / / File uploadFile: wxPromise (wx.uploadFile), downloadFile: wxPromise (wx.downloadFile), / / recording startRecord: wxPromise (wx.startRecord) / / playVoice: wxPromise (wx.playVoice), / / Music playback getBackgroundAudioPlayerState: wxPromise (wx.getBackgroundAudioPlayerState), playBackgroundAudio: wxPromise (wx.playBackgroundAudio), seekBackgroundAudio: wxPromise (wx.seekBackgroundAudio), / / Video chooseVideo: wxPromise (wx.chooseVideo), saveVideoToPhotosAlbum: wxPromise (wx.saveVideoToPhotosAlbum), / / File saveFile: wxPromise (wx.saveFile), getFileInfo: wxPromise (wx.getFileInfo), getSavedFileList: wxPromise (wx.getSavedFileList) GetSavedFileInfo: wxPromise (wx.getSavedFileInfo), removeSavedFile: wxPromise (wx.removeSavedFile), openDocument: wxPromise (wx.openDocument), / / data cache setStorage: wxPromise (wx.setStorage), getStorage: wxPromise (wx.getStorage), getStorageInfo: wxPromise (wx.getStorageInfo), removeStorage: wxPromise (wx.removeStorage), / / location getLocation: wxPromise (wx.getLocation), chooseLocation: wxPromise (wx.chooseLocation), openLocation: wxPromise (wx.openLocation) / device getSystemInfo: wxPromise (wx.getSystemInfo), getNetworkType: wxPromise (wx.getNetworkType), startAccelerometer: wxPromise (wx.startAccelerometer), stopAccelerometer: wxPromise (wx.stopAccelerometer), startCompass: wxPromise (wx.startCompass), stopCompass: wxPromise (wx.stopCompass), / / call makePhoneCall: wxPromise (wx.makePhoneCall), / / scan scanCode: wxPromise (wx.scanCode), / / clipboard setClipboardData: wxPromise (wx.setClipboardData) GetClipboardData: wxPromise (wx.getClipboardData), / / Bluetooth 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), / / screen brightness setScreenBrightness: wxPromise (wx.setScreenBrightness), getScreenBrightness: wxPromise (wx.getScreenBrightness), setKeepScreenOn: wxPromise (wx.setKeepScreenOn), / / Vibration vibrateLong: wxPromise (wx.vibrateLong), vibrateShort: wxPromise (wx.vibrateShort), / / contact 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) / / third-party platform getExtConfig: wxPromise (wx.getExtConfig), / / forward showShareMenu: wxPromise (wx.showShareMenu), hideShareMenu: wxPromise (wx.hideShareMenu), updateShareMenu: wxPromise (wx.updateShareMenu), getShareInfo: wxPromise (wx.getShareInfo), / / ship to address chooseAddress: wxPromise (wx.chooseAddress), / / Card coupon addCard: wxPromise (wx.addCard), openCard: wxPromise (wx.openCard) / / set openSetting: wxPromise (wx.openSetting), getSetting: wxPromise (wx.getSetting), / / Wechat campaign getWeRunData: wxPromise (wx.getWeRunData), / / Open Mini Program navigateToMiniProgram: wxPromise (wx.navigateToMiniProgram), navigateBackMiniProgram: wxPromise (wx.navigateBackMiniProgram), / / obtain invoice title chooseInvoiceTitle: wxPromise (wx.chooseInvoiceTitle), / / biometric checkIsSupportSoterAuthentication: wxPromise (wx.checkIsSupportSoterAuthentication) StartSoterAuthentication: wxPromise (wx.startSoterAuthentication), checkIsSoterEnrolledInDevice: wxPromise (wx.checkIsSoterEnrolledInDevice)}
The above is the basic api arrangement of Mini Program, which is posted for everyone's use.
Step 2 use import wxp from'. / lib/wxp'App ({... Wxp, async onLaunch () {const res = await wxp.getSystemInfo () console.log (res)}.}) the above content is how to make WeChat Mini Programs support async await. Have you learned the knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.