把微信小程序异步API转为Promise,简化异步编程
把微信小程序异步API转化为Promise。用Promise处理异步操作有多方便,谁用谁知道。
微信官方没有给出Promise API来处理异步操作,而官方API异步的又非常多,这使得多异步编程会层层回调,代码一复杂,回调起来就想砸电脑。
于是写了一个通用工具,把微信官方的异步API转化为Promise,方便处理(多)异步操作。
你可以这样用:
准备转化后的方法并暴露出
// /utils/wx-promise.js
import toPromise from '/module/to-promise/src/index'
const toPromiseWx = toPromsie(wx)
export const request = toPromiseWx('requset')
export const getLocation = toPromiseWx('getLocation')
export const setStorage = toPromiseWx('setStorage')
//export 其他你项目中可能用到的异步API
在其他文件中使用
在App.js中使用:
//App.js
import { request } from './utils/wx-promise.js'
App({
onLanuch: () => {
request({ url: 'http://api.yourapi.com' })
.then(() => {
//成功后处理
})
.then(() => {
//失败后处理
})
}
})
在其他page中使用:
// /page/index.js
import { request, setStorage } from '../utils/wx-promise.js'
page({
onLoad: () => {
request({ url: 'http://api.yourapi.com' })
.then(() => {
//成功后处理
})
.then(() => {
//失败后处理
})
},
onHide: () => {
setStorage({
key: 'yourkey',
data: 'yourvalue'
})
.then(() => {
//保存成功
})
.then(() => {
//保存失败
})
}
})
项目地址:to-promise
其他更多更具体用法,直接粘贴README了,如下。
to-promise是一个转换微信小程序异步API为Promise的一个工具库
优点:
- 避免小程序异步编程多次回调带来的过多回调导致逻辑不清晰,篇幅过长等问题。
- 借助于Promise异步编程特点,支持链式操作,像同步一样写异步。
- 转化后得API几乎和微信官方API一样。
使用方法:
- 安装
- 使用
git安装到项目根目录/module,
git clone https://github.com/tornoda/to-promise
- 或直接下载放入项目目录下如:
/module
- 在需要用到的地方引入
import toPromise from '/module/to-promise/src/index'
- 绑定微信全局对象(
wx)到函数,以便可以取到微信得API
const toPromiseWx = toPromise(wx)
- 开始转化你需要得异步API
//apiName为微信异步方法名,如对wx.request()进行转化
const request = toPromiseWx('request')
//直接使用request方法
举例:
import toPromise from '/module/to-promise/src/index'
//转换wx.getStorage()
const getStorage = toPromsie(wx)('getStorage')
//使用
getStorage({ key: 'test' })
.then(
(res) => {
//res的值与wx.getStorage({ success: (res) => {} })中的res值一样
//res = {data: 'keyValue'}
console.log(res.data)//控制台打印storage中key对于的value
return res.data//如果需要继续链式调用转化后的api,需要把值显示返回
},
(err) => {
//err的值与wx.getStorage({ success: (err) => {} })中的err值一样
throw err
}
)
关于Promise对象的使用,请参见Promise
API
- toPromise(global)
参数
(wx): wx全局对象。即toPromise(wx)这样调用
返回
(function): 参数(string)为小程序异步方法名。返回一个函数,该函数的参数与返回值如下。
参数:(object) 对应wx小程序异步方法中的参数(OBJECT)除去success与fail后的对象。例如:
官方APIwx.getLocation(OBJECT)的OBJECT接受如下属性: type altitude success fail complete,那么去除(success fail)后为:type altitude complete。
返回: (pending Promsise) 返回一个未知状态的Promise对象,在该对象上调用.then(onFulfilled, onRejected)方法来处理对用成功或失败的情况。onFulfilled为请求成功后调用的回调函数,参数为返回值,onRejected为请求失败后的回调函数,参数为返回的错误信息。
简单点来说,
const getLocation = toPromiseWx('getLocation')
getLocation({
type: 'wgs84',
altitude: true,
complete: () => { console.log('to-promsise is awesome') }
}).then(
(res) => {//dosomething if succeed},
(err) => {//dosomething if failed}
)
与下面官方调用等价
wx.getLocation({
type: 'wgs84',
altitude: true,
complete: () => { console.log('to-promsise is awesome') },
success: (res) => {//dosomething if succeed},
fail: (err) => {//dosomething if failed}
})
应用场景举例
- 单次异步调用,参见API最后
- 多次异步操作调用,且每下一次调用都会用到前一次返回的结果。
如:获得GPS信息后,根据GPS信息获取天气信息,取得天气信息后立马存入localStorage。
import toPromise from '/module/to-promise/src/index'
const toPromiseWx = toPrmise(wx)
//方法转换
const getLocation = toPromiseWx('getLocation')
const request = toPromiseWx('request')
const setStorage = toPromiseWx('setStorage')
//链式写逻辑
getLocation() //获取位置信息
.then(
(res) => { //位置获取成功后的处理,res为返回信息
//处理res后返回有用的信息,这里直接返回res,用于演示
return Promise.resolve(res) //必须
},
(err) => { //位置获取失败后的错误处理,err为错误信息
//错误处理
return Promise.resolve(err) //必须
}
)
.then(
(res) => { //根据位置获取成功后的信息,请求天气信息
return request({ url: 'http://api.weather.com'}) //返回一个pending 状态下的Promise
}
)
.then(
(res) => { //天气获取成功后存入storage的回调
setStorage({
key: 'test',
data: 'res'
})
},
(err) => {
//天气获取失败后执行这里,err为获取天气失败的错误信息
}
)
如果使用官方的API写上述逻辑,代码是这样的:
wx.getLocation({
success: (res) => {
//some transformation with res
wx.request({
url: 'http://api.weather.com',
success: (res) => {
wx.setStorage({
success: () => {
//do something
},
fail: (err) => {
//do something if err happend
}
})
},
fail: (err) => {
//do something if err happend
}
})
},
fail: (err) => {
//do something if err happend
})
//层层回调,如果逻辑再复杂点,可能就疯了
把微信小程序异步API转为Promise,简化异步编程的更多相关文章
- 微信小程序 HTTP API
微信小程序 HTTP API promise API https://www.npmtrends.com/node-fetch-vs-got-vs-axios-vs-superagent node-f ...
- 微信小程序通过api接口将json数据展现到小程序示例
这篇文章主要介绍了微信小程序通过api接口将json数据展现到小程序示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考.一起跟随小编过来看看吧实现知乎客户端的一个重要知识前提就是,要知道怎么通过 ...
- 图解微信小程序---调用API操作步骤
图解微信小程序---调用API操作步骤 什么是API API(Application Programming Interface,应用程序编程接口:是一些预先定义的函数,目的是提供应用程序与开发人员基 ...
- 微信小程序之 ----API接口
1. wx.request 接口 可在文件 wxs中操作,连接服务器处理数据 参数 ① url ② data ③ header ④ method ⑤ dataType 回调 ...
- 微信小程序-物流api
原来用的快递100的接口有变动,现有系统上不能使用了.查看快递100提供的api,探寻微信小程序端的使用情况.有几个是比较合适的:1.跳转api(https://www.kuaidi100.com/o ...
- 微信小程序请求API接口PHPSESSID变化的解决方式
微信小程序开发,请求服务器API的方法使用的是微信官方提供的wx.request()方法.在开发中发现,每一个请求都会生成一个独立的PHPSESSID,如下图示: 搜索后得知,这是由于wx.reque ...
- 微信小程序通过api接口将json数据展现到小程序上
实现知乎客户端的一个重要知识前提就是,要知道怎么通过知乎新闻的接口,来把数据展示到微信小程序端上. 那么我们这一就先学习一下,如何将接口获取到的数据展示到微信小程序上. 1.用到的知识点 <1& ...
- 微信小程序,时间戳转为日期格式
//数据转化 function formatNumber(n) { n = n.toString() ] ? n : ' + n } /** * 时间戳转化为年 月 日 时 分 秒 * number: ...
- 微信小程序调用api接口
请求的第三方微信url大概有3种 1)$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&s ...
随机推荐
- 05-C#笔记-基本变量
1. 不支持括号初始化: 2. 支持强制类型转化: 3.运算规则同C++ 参考: http://www.runoob.com/csharp/csharp-variables.html
- 重新学习Spring注解——声明式事务
36.声明式事务-环境搭建 37.声明式事务-测试成功 38.[源码]-声明式事务-源码分析 /** * 声明式事务: * * 环境搭建: * 1.导入相关依赖 * 数据源.数据库驱动.Spring- ...
- sublime3插件BracketHighlighter的配置
BracketHighlighter插件能为Sublime Text提供括号,引号这类高亮功能,但安装此插件后,默认没有高亮,只有下划线表示,不是很醒目,需要配置:1.在Sublime Text中用p ...
- selenium篇之滑动验证码
一.介绍 现在出现了一种通过用户鼠标移动滑块来填补有缺口图片的验证码,我们叫做滑动验证码.它的原理很简单,首先生成一张图片,然后随机挖去一块,在页面展示被挖去部分的图片,再通过js获取用户滑动距离,以 ...
- 请指出document load和document ready的区别
document load文档的所有内容都加载完成 document ready文档的DOM加载完成
- 09-排序2 Insert or Merge (25 分)
According to Wikipedia: Insertion sort iterates, consuming one input element each repetition, and gr ...
- Solr7.x学习(8)-使用spring-data-solr
1.maven配置 <dependency> <groupId>org.springframework.data</groupId> <artifactId& ...
- nginx+keepalived高可用及双主模式【h】
高可用有2中方式. 1.Nginx+keepalived 主从配置 这种方案,使用一个vip地址,前端使用2台机器,一台做主,一台做备,但同时只有一台机器工作,另一台备份机器在主机器不出现故障的时候, ...
- 【数据结构】【计算机视觉】并查集(disjoint set)结构介绍
1.简述 在实现多图像无序输入的拼接中,我们先使用surf算法对任意两幅图像进行特征点匹配,每对图像的匹配都有一个置信度confidence参数,来衡量两幅图匹配的可信度,当confidence> ...
- Shell脚本之一 Shell脚本简介
一.什么是shell? 我们平时所说的 Shell 可以理解为 Linux 系统提供给用户的使用界面.Shell 为用户提供了输入命令和参数并可得到命令执行结果的环境.当一个用户登录 Linux 之后 ...