小程序 请求Promise简单封装

最近做小程序在调用后台接口的时候感觉总写很长一串,很冗杂。非常想念vue中promise封装的写法,于是自己初步封装了一下。

1.url 接口地址

2.headers请求头

3. params 请求参数 

4.host 服务端地址

 

/** 字符串化 */
    export function stringifyQuery(query){
        let arr = [];
        for (let key in query) {
          let value = query[key];
          if (value == null) continue;
          arr.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
        }
        return arr.join("&");
    }
resolveUrl(path){
        if(path.startsWith("http://") || path.startsWith("https://")){
            return path;
        }
        return host + path;
    }
checkResponseStatus(response){
        if(!response.data) throw response;
        let message = response.data.message || "";
        let code = response.data.code;
        if (code == 200)
            return response.data;
        let err = Object.create(new Error(message));
        err.type = "apiResponseStatusError";
 
        /** 兼容 wx Error 结构 */
        err.errMsg = message;
        /** 代码中使用 code 判断不同错误状态 */
        err.code = code;
        /** 代码中使用 res 获取 code 不为 200 时的响应内容 */
        err.res = response.data;
 
        throw err;
    }
apiRequest(option){
    let resolve, reject;
    let promise = new Promise((s,j)=>{
        resolve = s
        reject = j
    })
    let defaultHeader = {}
    let heard =  option.headers = Object.assign({}, option.header, defaultHeader);
    option.headers = option.header
    let headerParam = stringifyQuery(header)
    option.url += option.url.includes("?")
     ? "&" + headerParam : headerParam? "?" + headerParam : "";
    let proxySuccess = function(res){       
        let response = res.data;
        let header = res.header;
        let httpStatus = res.statusCode;
        let status = response.status;
        return resolve(res);
     }
     let proxyFail = function(err){
            let msg = err.errMsg;
            if(msg && msg.includes("max connected")){
                option._retryCount = (option._retryCount || 0) + 1;
                option._retryCount > 4
                    ? reject(err)
                    : setTimeout(_ => uni.request(option), 300);
                return;
            }
            if(msg && msg.includes("request:fail")){
                let e = new Error("请求失败, 请检查网络")
                e.innerError = err;
                err = e;
            }
            if(msg && msg.includes("fail to connect")){
                let e = new Error("连接失败, 稍后再试")
                e.innerError = err;
                err = e;
            }
            reject(err);
        }
    option.success = proxySuccess;
    option.fail = proxyFail;
    option.complete = proxyComplete;
    wx.request(option);
    return promise;
}

 

POST:

post(path){
    let getApi = data =>
    apiRequest({
        url:resolveUrl(path),
        data: data
    })
    .then(checkResponseStatus);
    getApi.path = path;
    return getApi; 
}

 

GET:

get(path){
    let getApi = data =>
    apiRequest({
        url:resolveUrl(path),
        data: data
    })
    .then(checkResponseStatus);
    getApi.path = path;
    return getApi; 
}

 

到这儿呢就结束了,就可以愉快的通过then来取回调了。

当然在这里还可以做错误统一处理,我这儿只是简单的做了封装,有兴趣的小伙伴可以进一步封装。

本人小白,如有错误欢迎指正批评。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

posted @ 2019-09-16 16:16  小白来袭  阅读(604)  评论(0编辑  收藏  举报