微信小程序网络请求封装

1,344 阅读1分钟

利用promise封装常用请求

const baseUrl = 'https://api.smart.com'

//封装http请求
const http = ({url='',param={},...other}=>{})=>{
        wx.showLoading({
            title:'请稍后...'
        });
        let timeStart = Date.now();
        return new Promise((resolve,reject)=>{
            wx.request({
                url:getUrl(url),
                data:param,
                header:{
                    content-type:'application/json'
                },
                ...other,
                complete:(res)=>{
                    wx.hideLoading();
                    console.log(`耗时$(Date.now()-timeStart)`);
                    if(res.statusCode>=200 && res.statusCode<300){
                        resolve(res.data)
                    }else{
                        reject(res)
                    }
                }
            })
        })
        
    //截取、得到路径
    const getUrl=(url)=>{
        if(url.indexOf('://')==-1){
            return baseUrl + url
        }else{
            return url
        }
    }
    
    //get方法
    const _get = (url,param={})=>{
        return http({
            url,
            param
        })
    }
    //post方法
    const _post = (url,param={})=>{
        return http({
            url,
            param,
            method:'post'
        })
    }
    //put方法
    const _put = (url,param={})=>{
        return http({
            url,
            param,
            method:'put'
        })
    }
    //delete方法
    const _delete = (url,param={})=>{
        return http({
            url,
            param,
            method:'put'
        })
    }
    
    module.exports = {
        baseUrl,
        _get,
        _post,
        _put,
        _delete
    }
}

如何使用

const api = require('封装的请求路径')
apt.get(url,param,...other).then(res=>{
    
}).catch(e=>{
    console.log(e)
})

//假如连续多个请求
Promise.all([
api.get(),
api.post()
]).then(res=>{
    //todo
}).catch(e=>{
    //todo
})