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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM