超簡單 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'
            })
        }
    });
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM