导航

使用async/await封装uni-app请求

Posted on 2020-08-03 11:14  WinChance  阅读(4496)  评论(0编辑  收藏  举报

直接上代码:

// 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);
            }
        });
    })
}