微信小程序对于回调函数异步API的优化

默认情况下,小程序官方提供的异步API都是基于回调函数实现的,基于回调函数的异步API,虽然可以处理一些需要等待的操作,如网络请求,但其设计模式也存在一些缺点:

  1. 回调地狱 :当一个操作需要依赖另一个操作的结果时,如果使用回调函数,很容易导致代码嵌套层次深,可读性,维护性差 ,这种情况被称为“回调地狱”
  2. 代码组织困难 :由于回调函数通常是异步执行的,这使得它在代码组织上带来困难。你不得不考虑异步操作的顺序,以及如何处理错误和成功情况,这往往使得代码结构变得复杂
  3. 错误处理不便 :在回调函数模式中,错误处理通常需要在回调函数内部进行,而且如果在一个异步操作中发生了错误,很难将错误信息传递回上层逻辑进行处理

解决方案:

在小程序中,实现 APl Promise 化主要依赖于 miniprogram-api-promise 这个第三方的npm 包。

通过额外的配置,将官方提供的、基于回调函数的异步APl,升级改造为基于Promise的异步APl,从而提高代码的可读性、维护性,避免回调地狱的问题。

在小程序的根目录中,调用终端安装miniprogram-api-promise包

npm install --save miniprogram-api-promise@1.0.4

在小程序入口文件中(app.js),只需调用一次promisifyAll()方法

// app.js
//在小程序入口文件中(app.js),只需调用一次promisifyAll()方法
//即可实现异步API的Promise化
import{promisifyAll}from'miniprogram-api-promise'
const wxp = wx.p= {}
//promisify all wx's api
promisifyAll(wx,wxp)
//把wx对象挂载到空对象wxp身上
App({
})

在页面中调用API

基于回调函数的异步APl的wx.request

getColors()
{
  this.setData({
    isLoading:true
  }),
  wx.showLoading({
    title: '加载中',
  }),
  wx.p.request({ //增加const res = await wx.p.request
    url: 'http://192.168.64.128/found.php?',
    method:"get",
    header:{'content-type': 'application/x-www-form-urlencoded'},
    data:{
      id1:this.data.x+this.data.sumStep,
      id2:this.data.y+this.data.sumStep
    },
    success:(res)=>{
      console.log("here"),
      this.setData({
        //旧数据展开,新数据拼接
        colorList:[...this.data.colorList,...res.data],
        x:5,
        y:7,
        sumStep:this.data.sumStep+this.data.step
      })
    },
    complete:()=>{
      setTimeout(()=>
      {
        wx.hideLoading({
        })
      }, 1*1000),
      this.setData({
        isLoading:false
      })
    },
  })
},

基于Promise的异步APl的wx.p.request

async getColors() {
    this.setData({ isLoading: true });
    wx.p.showLoading({ title: '加载中' });
    try {
      const { data: res } = await wx.p.request({
        url: 'http://192.168.64.128/found.php?',
        method: "get",
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: {
          id1: this.data.x + this.data.sumStep,
          id2: this.data.y + this.data.sumStep
        }
      });
      this.setData({
        colorList: [...this.data.colorList, ...res],
        x: 5,
        y: 7,
        sumStep: this.data.sumStep + this.data.step
      });
    } finally {
      setTimeout(() => {
        wx.p.hideLoading();
        this.setData({ isLoading: false });
      }, 1000);
    }
  },
  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

睡不着乌托托

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值