zoukankan      html  css  js  c++  java
  • 使用async/await封装uni-app请求

    直接上代码:

    // async版get请求
    async function getAsync(url, data) {
        uni.showLoading({
            title: '数据加载中...',
            mask: true
        });
    
        let [err, res] = await uni.request({
            url: _BASE_URL + url,
            method: 'GET',
            data: data,
            header: {
                'content-type': 'application/json',
                'Cookie': 'JSESSIONID=' + util.getStorage('sessionId')
            }
        });
    
        uni.hideLoading();
        if (res) {
            return res.data;
        }
    
        if (err) {
            uni.showToast({
                title: '请求超时!',
                icon: 'none',
                mask: true,
                duration: 2000
            });
        }
    }

    其他方案:

    // Promise版
    async function getPromise(url) {
        return new Promise((resolve, reject) => {
            uni.request({
                url: _BASE_URL + url,
                method: 'GET',
                header: {
                    'content-type': 'application/json',
                    'Cookie': 'JSESSIONID=' + util.getStorage('sessionId')
                },
                success: (res) => {
                    if (1 == res.data.code) {
                        uni.hideLoading();
                        resolve(res.data);
                    } else {
                        uni.hideLoading();
                        uni.showToast({
                            title: res.data.msg,
                            icon: 'none',
                            mask: true,
                            duration: 2000
                        });
                        resolve(res.data);
                    }
                },
                fail: (err) => {
                    uni.hideLoading();
    
                    if (util.getStorage('mark') == 0) {
                        uni.showToast({
                            title: '请求超时!',
                            icon: 'none',
                            mask: true,
                            duration: 2000
                        });
                    } else {
                        uni.showToast({
                            title: 'Request timed out!',
                            icon: 'none',
                            mask: true,
                            duration: 2000
                        });
                    }
                    reject(err);
                }
            });
        })
    }
  • 相关阅读:
    骨场经历
    聚财与聚人
    腾讯正式开始了QQForMAC的测试
    fiddler
    soap协议基本结构
    js小判断
    控制器
    resharper快捷键
    如何让datetime类型数据接受并且产出long或string类型?
    AES加密,解密方法
  • 原文地址:https://www.cnblogs.com/winchance/p/13425227.html
Copyright © 2011-2022 走看看