![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLjF2Y1MDNwIzN5czMyU2NhVjZ0QTMkhjMiVWZ5MWYmdzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
在這篇小程式API的Promise化文章中講到小程式官方提供的異步API都是基于回調函數來實作的,在大量的使用這種回調函數就會造成回調地獄的問題,以及代碼的可讀性和可維護性差,通過對小程式API的Promise化能解決,那麼本篇是來講進行對微信小程式網絡資料請求的接口請求封裝。
封裝小程式 request 請求
在 /utils 目錄下建立 request.js 檔案進行小程式request請求的封裝:
// 封裝資料請求request
const BASE_URL = ''; // 基礎位址
export default function request(url,params={}){
return new Promise((resolve,reject)=>{
wx.showLoading({ // 請求提示
title: '正在加載中...',
})
wx.request({
url: BASE_URL + url, // 請求url位址
data: params.data || {}, // 請求參數
header: params.header || {}, // 請求頭
method: params.method || 'GET', // 請求方式
dataType: 'json', // 傳回資料類型
success: (res)=> { // 成功調用
wx.hideLoading(); // 關閉請求提示
resolve(res.data) // 成功處理res.data中的資料
},
fail: (err)=> { // 失敗調用
wx.hideLoading(); // 關閉請求提示
wx.showToast({ // 提示錯誤資訊
title: err || '請求錯誤!',
})
reject(err) // 失敗處理err
}
})
})
}
對于request的網絡資料請求的封裝并沒有那麼的複雜,加上一些注釋小白應該可以更容易了解,在未 return new Promise(..) 之前傳回的是一個Promise對象,這時可以再 new 一個Promise拿到資料,它有兩個參數,兩個參數分别又是函數,即高階函數;請求之前使用wx.showLoading提示請求在加載中,通過wx.request發起資料請求,與基礎位址BASE_URL拼接,通過data接收傳入參數,header、method同理,success成功調用關閉掉請求提示交給resolve處理成功結果,fail失敗調用關閉掉請求提示,同時需要提示使用者請求錯誤的資訊後交給reject處理失敗結果;
如何來調用封裝的request請求呢?
首先先來準備一下資料請求的測試接口,這裡通過本地Node.js搭載的伺服器提供的API接口進行測試:
測試接口已經準備完成,設定一下 BASE_URL 基礎位址為 http://127.0.0.1:3000;
const BASE_URL = 'http://127.0.0.1:3000'
這裡需要設定【選中】微信小程式開發者工具中的【詳情】- 【不校驗合法域名...】這項;
在 index.wxml 中設定一個按鈕:
<button bindtap="handleClick">request請求</button>
在 index.js 中引入封裝request資料請求檔案,并編寫按鈕的觸發事件 handleClcik:
// index.js
const app = getApp()
import request from '../../utils/request'
Page({
handleClick(){
request('/api/navList').then(res=>{
console.log(res);
})
}
})
封裝各資料接口請求函數
項目中用着許許多多的接口資料請求,此時對于這些接口函數進行封裝處理,使用的時候可以直接來導入使用;
建立 /util/api.js 檔案封裝各接口請求函數的檔案:
// 引入封裝request請求函數
import request from './request'
// 擷取swiperList資料
export const reqSwiperList = () => request('/api/swiperList')
// 擷取navList資料
export const reqNavList = () => request('/api/navList')
// 擷取category資料
export const reqCategory = () => request('/api/category')
下面在 index.js 中的onLoad中來調用使用:
...
onLoad:function(){
reqSwiperList().then(res=>{console.log('reqSwiperList',res)});
reqNavList().then(res=>{console.log('reqNavList',res)});
reqCategory().then(res=>{console.log('reqCategory',res)});
}
...
async 和 await
通過 async 和 await 的寫法會比使用 .then(res=>{}) 的這種方式更加簡練一些;下面來将 handleClick 中的請求函數做一個變更:
handleClick(){
reqSwiperList().then(res=>{
console.log(res);
})
}
使用 async 和 await 寫法:
async handleClick(){
const res = await reqSwiperList()
console.log(res)
}
以上就是封裝小程式request資料請求和封裝各接口資料請求函數的内容;可以在你的小程式項目當中去使用,封裝小程式的request請求和封裝各接口請求,可以讓你在小程式項目中更上一層!感謝大家的支援!!!