当前位置:网站首页>小程序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
边栏推荐
- Unity3D Application simulation enters the front and background and pauses
- cnpm安装步骤
- Stimulsoft ReportsJS and DashboardsJS. 2022.3.3
- 1. 获取数据-requests.get()
- What is the data directory?Why do you need it?
- Go 学习笔记(84)— Go 项目目录结构
- Classification of decision tree classification
- The 2nd Shanxi Province Network Security Skills Competition (Enterprise Group) Partial WP (10)
- Thinkphp 5.0.24变量覆盖漏洞导致RCE分析
- 基于OpenCV实现的图像拼接(配准)案例
猜你喜欢
Thinkphp 5.0.24变量覆盖漏洞导致RCE分析
MySql 怎么查出符合条件的最新的数据行?
【周周有奖】云原生编程挑战赛“边缘容器”赛道邀你来战!
基于OpenCV实现的图像拼接(配准)案例
[Linear table] - Detailed explanation of three practice questions of LeetCode
sql statement - how to query data in another table based on the data in one table
cnpm installation steps
【线性表】- LeetCode力扣三道练习题详解
Go 学习笔记(84)— Go 项目目录结构
handler+message【消息机制】
随机推荐
DAY17、CSRF 漏洞
Shanxi group (enterprises) in the second network security skills competition part problem WP (7)
Go study notes (84) - Go project directory structure
My first experience of Go+ language——Blessing message system, so that she can also feel your blessings
[SQL] at a certain correlation with a table of data update another table
图像视角矫正之透视变换矩阵(单应矩阵)/findHomography 与 getPerspectiveTransformd的区别
Web page element parsing a tag
Unity beginner 5 cameras follow, border control and simple particle control (2 d)
模拟问题(上)
@ WebServlet annotations (Servlet annotations)
数据目录是什么?为何需要它?
js 操作在当前日期加减(天、周、月、年数)
【MySQL系列】-B+树索引和HASH索引有什么区别
handler+message [message mechanism]
权值线段树+线段树分裂/合并+CF1659D
双指针问题(下)
Chapter8 支持向量机
Excellent MySQL interview questions, 99% must ask in preparation for August!I can't pass the interview
labelme的使用技巧
商品管理系统数据库设计--SQL Server