当前位置:网站首页>小程序npm包--API Promise化
小程序npm包--API Promise化
2022-07-30 04:36:00 【像费曼%】
1.基于回调函数的异步API的缺点
默认情况下,小程序官方提供的异步API都是基于回调函数实现的,例如,网络请求的API需要按照如下的方式调用:
wx.request({
method:'',
url:'',
data:{},
success:()=>{},//请求成功的回调函数
fail:()=>{},//请求失败的回调函数
complete:()=>{}//请求完成的回调函数
})缺点:容易造成回调地狱的问题,代码的可读性、维护性差!
2.什么是API Promise化
API Promise化,指的是通过额外的配置,将官方提供的、基于回调函数的异步API,升级改造为基于Promise化的异步API,从3.而提高代码的可读性、维护性、避免回调地狱的问题
3.实现Promise化
在小程序中,实现API Promise化主要依赖于miniprogram-api-promise这个第三方的npm包。
npm i --save [email protected]
//app.js
import{ promisifyAll } from 'miniprogram-api-promise'
const wxp = wx.p={}
promisifyAll(wx,wxp)
4.调用Promise化之后的异步API
//页面.js
async getInfo(){
const{data: res }=await wx.p.request({
method:'GET',
url:'https://www.escook.cn/api/get',
data:{
name:'zs',
age:20
}
})
console.log(res)
},
//页面.wxml
<vant-button type="danger" bindtap="getInfo">按钮</vant-button> 
关于非Promise化的微信回调函数可参考文章:http://t.csdn.cn/yPCxV
边栏推荐
- 《构建之法》笔记---第十章 典型用户和场景
- 3. Dependency configuration management
- error: The following untracked working tree files would be overwritten by
- 2.6 Merge Sort
- 解决go环境编译不了exe
- See you in shenzhen!Cloud native to accelerate the application building special: see cloud native FinOps, SRE, high-performance computing scenario best practices
- Go 学习笔记(84)— Go 项目目录结构
- 模拟问题(上)
- Notes on "The Law of Construction"---Chapter 10 Typical Users and Scenarios
- sql statement - how to query data in another table based on the data in one table
猜你喜欢
随机推荐
SVN 查看用户名密码
1. 获取数据-requests.get()
DAY17, CSRF vulnerability
Introduction to Thymeleaf
How to use labelme
@WebServlet注解(Servlet注解)
@ WebServlet annotations (Servlet annotations)
Verify that the addShutdownHook hook takes effect
webService接口
MySQL 操作语句大全(详细)
(Problem practice) Conditional probability + weight line segment tree + FWT + suffix array
cnpm installation steps
获取本机IP和Request的IP
双指针问题(上)
C. Travelling Salesman and Special Numbers (binary + combination number)
3. Dependency configuration management
QT(39)-vs development qt program prompts that the source file cannot be opened
动态规划问题(完结篇)
山西省第二届网络安全技能大赛(企业组)部分赛题WP(八)
小程序 wx.miniProgram.navigateTo 跳转地址不能是tabbar地址








