微信小程序API wx.request 使用Promise封装 统一请求入口 统一异常处理

微信小程序API wx.request 使用Promise封装 统一请求入口 统一异常处理

http封装js:httpService.js

import {
    Host
} from "./constants.js";

function handleSuccess(result) {
    wx.hideLoading();
}

function handleError(error) {
    var errorCode = error.statusCode;
    if (errorCode == 401) {
        wx.showLoading({
            title: "请先登录"
        });
    } else if (errorCode == 500) {
        if (wx.getStorageSync("token") == "") {
            wx.showToast({
                title: "请先登录",
                icon: "none",
                duration: 2000
            });
        } else {
            wx.showToast({
                title: error.data.error.message + "",
                icon: "none",
                duration: 3000
            });
        }
    } else {
        wx.showLoading({
            title: "网络故障"
        });
    }
}

function header() {
    var head = {
        Authorization: wx.getStorageSync("token")
    };
    return head;
}

function wxPromisify(fn) {
    return function (obj = {}) {
        return new Promise((resolve, reject) => {
            obj.success = function (result) {
                if (result.data.success) {
                    handleSuccess(result);
                    resolve(result.data);
                } else {
                    resolve(result.data);
                    handleError(result);
                }
            };
            obj.fail = function (error) {
                handleError(error);
                reject(error);
            };
            fn(obj);
        });
    };
}

//无论promise对象最后状态如何都会执行
Promise.prototype.finally = function (callback) {
    let P = this.constructor;
    return this.then(
        value => P.resolve(callback()).then(() => value),
        reason =>
            P.resolve(callback()).then(() => {
                throw reason;
            })
    );
};
function checklogin() {

}

function Post(url, paramObj, ischeck) {
    var getRequest = wxPromisify(wx.request);
    if (!ischeck) {
        checklogin()
    }
    return getRequest({
        url: Host + url,
        data: paramObj,
        header: header(),
        method: "POST"
    });
}

function Get(url, ischeck) {
    var getRequest = wxPromisify(wx.request);
    if (!ischeck) {
        checklogin()
    }
    return getRequest({
        url: Host + url,
        header: header(),
        method: "GET"
    });
}

function Delete(url) {
    var getRequest = wxPromisify(wx.request);
    return getRequest({
        url: Host + url,
        header: header(),
        method: "DELETE"
    });
}

function Put(url, paramObj) {
    var getRequest = wxPromisify(wx.request);
    return getRequest({
        url: Host + url,
        data: paramObj,
        header: header(),
        method: "PUT"
    });
}

export const httpService = {
    get: Get,
    post: Post,
    delete: Delete,
    put: Put
};

使用方式

  1. 直接调用,业务页js直接调用, 如:index.js 直接调用 httpservice.js 中的方法
  2. [推荐] 按业务类型封装业务,例如用户处理的各类请求可以统一封装为 userService.js,index.js(业务page)---> 调用userService.js(业务封装js)---> 调用httpService.js(http封装js)

使用示例

1. userService.js

import {
    httpService
} from "./httpService";
import {
    SetWechatUserInfo,
    GetUserInfo,
    SetUserPhone,
    GetMyGifts
} from "./constants";


function setUseInfo(paramObj) {
    return httpService.post(SetWechatUserInfo, paramObj, true);
}

function getUserInfo(paramObj) {
    return httpService.post(GetUserInfo, paramObj, true);
}

function setUserPhone(paramObj) {
    return httpService.post(SetUserPhone, paramObj, true);
}

function getMyGifts(paramObj) {
    return httpService.get(GetMyGifts, paramObj, true);
}


export const userService = {
    setUseInfo,
    getUserInfo,
    setUserPhone,
    getMyGifts
};

2. index.js 片断

...
import {
    userService
} from '../../providers/userService';
...
...
function setUseInfo(input, userResult, cd) {
    userService.setUseInfo(input).then(res => {
        if (res.success) {
            if (res.success) {
                wx.switchTab({
                    url: '/pages/index/index'
                })
            }
            wx.setStorageSync("userInfo", userResult.userInfo)
            app.globalData.userInfo = userResult.userInfo
        }
    }).then(() => {
        cd()
    });
}
...

2. constants.js

export const Host = 'http://localhost:6234/';

export const Login = 'oauth2/token';
export const SetWechatUserInfo = 'api/****************';
export const GetUserInfo = 'api/****************';
export const SetUserPhone = 'api/****************';
export const GetMyFriends = 'api/****************';
export const GetBoostingLeaderboard = 'api/****************';

3. 小程序目录结构

posted @ 2020-05-13 23:17  eedc  阅读(1098)  评论(0编辑  收藏  举报