91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何使微信小程序支持async await

發布時間:2021-09-24 11:47:00 來源:億速云 閱讀:202 作者:柒染 欄目:移動開發

本篇文章為大家展示了如何使微信小程序支持async await,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

微信小程序并不支持async,寫起代碼來太不舒服了.  
各種回調會造成回調地獄的問題,回調函數一層套著一層,代碼難以閱讀,后期難以維護的問題

解決辦法:

使用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 封裝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)
    }
}

/**
 * 設置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,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

宁都县| 若尔盖县| 浮山县| 贺州市| 蒙山县| 墨竹工卡县| 泰顺县| 保定市| 墨脱县| 洪泽县| 正宁县| 漳平市| 罗源县| 庄浪县| 西峡县| 雅江县| 搜索| 曲沃县| 中卫市| 册亨县| 建始县| 宜都市| 察雅县| 通州区| 宜君县| 五华县| 莱州市| 宽城| 伊春市| 富平县| 隆林| 大新县| 朝阳市| 民勤县| 敖汉旗| 山阴县| 枣阳市| 吉水县| 方城县| 临潭县| 彭山县|