失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 【微信小程序】使用Promise 实现对wx.request()请求封装

【微信小程序】使用Promise 实现对wx.request()请求封装

时间:2021-04-18 16:25:49

相关推荐

【微信小程序】使用Promise 实现对wx.request()请求封装

写在前面

我们在使用wx.request()请求网络操作的时候,里面的参数参数说多也不多,说少也不少,一旦请求多了,这写起来就很繁琐,而且一旦某些参数有变动,这修改起来太费事了。

wx.request()是一个异步 API它的结果返回的是Promise,微信小程序基础库 2.10.2 版本起,异步 API 支持callback&promise两种调用方式。

现在使用使用Promise实现对wx.request()请求封装,可以帮助我们减少一些不必要的重复无用功。

具体实现

在小程序项目的utils下,新建一个request.js:,在这个文件里实现对wx.request()的封装:

request.js:

const baseURL = 'http://demo.';/*** 使用Promise 对wx.request进行分装* @param {*} params */function request(params = {methods, url, data }) {return new Promise(function (resolve,reject) {wx.request({url: baseURL + params.url,method: params.method,data: params.data ? JSON.stringify(params.data) : null,header: {'Content-Type': 'application/json','accessToken': ''},timeout: 5000,success(res) {if (res.statusCode == 200) {if (res.data.code == 0) {resolve(res.data);} else {wx.showToast({title: '提示',content: res.data.msg,showCancel: false,success:function(res) {}})reject(res,data);}} else {wx.showToast({title: '提示',content: '网络请求超时!',showCancel: false,success: function(res) {}})reject();} },fail (err) {reject(err)}})})}module.exports = {request: request}

新建api文件夹,在新建的js文件中,导入request.js,并实现封装增删改查的方法,命名自定义:

index.js:

const {request } = require('../utils/request');// 获取全部数据function getList() {return request({url: '/manager/list', method: 'GET'})}// 模糊查询function getItemIds(params) {return request({url: '/manager/items?keyword=' + params,method: 'GET',params: params})}// 新增function insertItem(params) {return request({url: '/manager/list'method: 'POST',data: params})}// 更新function updateItem(params) {return request({url: '/manager/list'method: 'PUT',data: params})}// 删除function deleteItem(id) {return request({url: '/manager/list'method: 'DELETE',params: id})}module.exports = {getList,insertItem,deleteItem,updateItem,getItemIds}

如何使用

下面使用实现获取全部数据 & 关键词查询:

// index.jsconst app = getApp();const mRequest = require('../../api/index')Page({data: {showItem: true, // 是否显示列表数据searchList: [], // 查询列表itemList: [], // 全部数据列表keyword: '', // 查询关键词roomId: undefined},// 加载列表数据onLoad() {const that = thismRequest.getList().then(res => {if (res) {// console.log(res);let listData = res.data;if (listData == null) {wx.showToast({title: '获取数据失败' + res.data.msg,icon: 'error',duration: 2000});} else {that.setData({showItem: true,itemList: res.data.items})}}}).catch(err => {console.log('error: ', err);that.setData({showItem: false})})},// 搜索/查询toSearch(e) {const that = this;console.log(that.data.keyword);mRequest.getItemIds(that.data.keyword).then(res => {if (res.data.items.length == 0) {wx.showToast({title: '暂无数据~',icon: 'loading',duration: 2000})} else {console.log(res);let searchList = res.data.items;that.setData({itemList: searchList})wx.showToast({title: '查询成功',duration: 2000})}}).catch(err => {console.log('error:', err);that.setData({showItem: false})})},})

返回的数据

如果觉得《【微信小程序】使用Promise 实现对wx.request()请求封装》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。