zoukankan      html  css  js  c++  java
  • 微信小程序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. 小程序目录结构

  • 相关阅读:
    JS实现前台表格排序功能
    openoffice安装手记
    OpenOffice 实现OFFICE在线预览
    毫秒事件转换小方法
    axis2 jar包详解及缺少jar包异常分析
    Android EditText控件完美实现只读(ReadOnly/NonEditable)
    android:获取联系人信息(姓名和电话)
    dex2jar.bat反编译apk的classes.dex文件错误:
    服务器压力测试系列二:服务器监控工具tsar安装
    memcache list all keys
  • 原文地址:https://www.cnblogs.com/eedc/p/12885647.html
Copyright © 2011-2022 走看看