您好,欢迎来到宝玛科技网。
搜索
您的当前位置:首页解决小程序 callback hell

解决小程序 callback hell

来源:宝玛科技网

写一个授权通用方法。

const _authHandle = (setting ,callback) => {
    wx.getSetting({
        success: (response) => {
            if (response.authSetting[setting]) {
                return callback(true)
            }

            wx.authorize({
                scope: setting,
                success: () => {
                    return callback(true)
                },
                fail: () => {
                    return callback(false)
                }
            })
        }
    })
}
复制代码

usage

_authHandle('scope.userInfo',(result) => {
  console.log(result)
})
复制代码

Promise

我们用 promise 稍微修改一下之前的函数~

const _authHandle = (setting) => {
    return new Promise((resolve, reject) => {
        wx.getSetting({
            success: (response) => {
                if (response.authSetting[setting]) {
                    resolve(true)
                }
    
                wx.authorize({
                    scope: setting,
                    success: () => {
                        resolve(true)
                    },
                    fail: () => {
                        reject(false)
                    }
                })
            }
        })
    })
}
复制代码

usage

_authHandle('scope.userInfo')
    .then(res => {
        // res
    })
    .catch(err => {
        // err
    })
复制代码

async/await

原生小程序里面使用 async/await ,需要引入 的 regenerator-runtime

去 github 上把文件下到 lib 文件内,可以新建一个叫 runtime 的文件夹,丢进去。

import regeneratorRuntime from'../../lib/runtime.js'
复制代码

usage

async onTapAuth () {
    await _authHandle('scope.userInfo')
        .then(() => {
            // yes
        })
        .catch(() => {
            // no
        })
}
复制代码

注意: await 总是返回一个 Promise 对象,所以可以使用 then catch 捕获异常,或者使用同步 try catch 捕获异常。推荐使用 then catch

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baomayou.com 版权所有 赣ICP备2024042794号-6

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务