当前位置:网站首页>小程序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
边栏推荐
猜你喜欢
sql语句-如何以一个表中的数据为条件据查询另一个表中的数据
Discourse 自定义头部链接(Custom Header Links)
Go 学习笔记(84)— Go 项目目录结构
VUX Datetime 组件compute-days-function动态设置日期列表
Thymeleaf简介
五、视图解析与模板引擎
【 notes 】 the beauty of the software engineering - column 31 | software testing are responsible for the quality of products?
protobuf 中复合数据类型的读写
BGP的简单实验
动态规划问题(完结篇)
随机推荐
C. Travelling Salesman and Special Numbers (binary + combination number)
【软件工程之美 - 专栏笔记】31 | 软件测试要为产品质量负责吗?
Golang eight-legged text finishing (continuous handling)
机器学习:知道通过低方差过滤实现降维过程
获取本机IP和Request的IP
Introduction to database - MySQL simple introduction
MySQL 操作语句大全(详细)
(Problem practice) Conditional probability + weight line segment tree + FWT + suffix array
Weight line segment tree + line segment tree split/merge + CF1659D
error: The following untracked working tree files would be overwritten by
How to use labelme
[Linear table] - Detailed explanation of three practice questions of LeetCode
七、自定义配置
Xiamen SenseCore Technology MC3172(1): Introduction and Environment Construction
Web page element parsing a tag
sql statement - how to query data in another table based on the data in one table
Discourse 自定义头部链接(Custom Header Links)
SVN 查看用户名密码
数据库概论 - MySQL的简单介绍
Stimulsoft ReportsJS and DashboardsJS. 2022.3.3