1. 程式人生 > 實用技巧 >使用async/await封裝uni-app請求

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