超简单 Promise封装小程序ajax 超好用 以及封装登录

//网络类

//封装网络请求

const ajax = (ajaxData, method) => {
    wx.showLoading({
        title: '加载中',
        mask: true
    });
    console.log('use ajax', ajaxData.url)
    return new Promise((resolve, reject) => wx.request({
        url: ajaxData.url,
        method: method || 'GET',
        data: ajaxData.data,
        success(e) {
            // console.log('ajax',e);
            if(e.data.retcode == 0) {
                resolve(e)
                wx.hideLoading();
            } else {
                wx.showToast({
                    title: e.data.message,
                    icon: 'none'
                })
                reject(e)
            }
        },
        fail(e) {
            wx.showLoading({
                title: '网络错误'
            })
        }
    }))
}

 调用:

对应的JS页面头部引入

let util = require('../../utils/util')
    var url = "https://api.map.baidu.com/geocoder/v2/";
    var params = {
      ak: "btdLALhz2PRv8iqW6oT95l6p", //免费去百度地图上申请一个
      output: "json",
      location: latitude + "," + longitude
    }

    util.ajax({
      url,
      data: params
    }).then(res => {
      console.log(res);
    })

或者将数据交互和逻辑分离开来,需要用的时候再调用

var url = "https://api.map.baidu.com/geocoder/v2/";
    var params = {
      ak: "btdLALhz2PRv8iqW6oT95l6p", //免费去百度地图上申请一个
      output: "json",
      location: latitude + "," + longitude
    }

    let planAjax = util.ajax({
      url,
      data: params
    })
    
   planAjax.then(res => {
      console.log(res);
    })
//判断是否登录
const checkLogin = () => {
    return new Promise((resolve, reject) => {
        let token = wx.getStorageSync('token');
        let userId = wx.getStorageSync('userId');
        //验证token是否存在
        if(token && userId) {
            //验证token是否过期
            ajax({
                url: API + 'account/checktoken',
                data: {
                    userId,
                    token
                }
            }).then(e => {
                //未过期 开始执行业务逻辑
                resolve();
            }).catch(e => {
                // 过期 清空本地所有存储 返回到登录页面
                if(e.data.retcode == 99) {
                    wx.removeStorageSync('token');
                    wx.removeStorageSync('userId');
                    wx.reLaunch({
                        url: '../login/login'
                    })
                }
            })
        } else {
            // token 不存在 未登录过 返回到登录页面
            // 执行清空 保证正确
            wx.reLaunch({
                url: '../login/login'
            })
        }
    });
}
原文地址:https://www.cnblogs.com/likewpp/p/9456224.html