微信小程序异步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](http://api.yourapi.com/)'` `})`
`.then(() => {`
`//成功后处理`
`})`
`.then(() => {`
`//失败后处理`
`})`//欢迎加入全栈开发交流圈一起学习交流:864305860
`}`
`})`
复制代码

在其他page中使用:

`// /page/index.js`
`import { request, setStorage } from` `'../utils/wx-promise.js'`
`page({`
`onLoad: () => {`
`request({ url:` `'[http://api.yourapi.com](http://api.yourapi.com/)'` `})`
`.then(() => {`
`//成功后处理`
`})`
`.then(() => {`
`//失败后处理`
`})`
`},`
`onHide: () => {`
`setStorage({`
`key:` `'yourkey'``,`
`data:` `'yourvalue'`
`})`
`.then(() => {`
`/保存成功`
`})`
`.then(() => {`
`//保存失败`
`})`
`}`//欢迎加入全栈开发交流圈一起学习交流:864305860
`})`
复制代码

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(//欢迎加入全栈开发交流圈一起学习交流:864305860
  (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
  }
 )//欢迎加入全栈开发交流圈一起学习交流:864305860
复制代码

返回 (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',//欢迎加入全栈开发交流圈一起学习交流:864305860
 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](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](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`
`}`//欢迎加入全栈开发交流圈一起学习交流:864305860
`})`//面向1-3年前端人员
`},`//帮助突破技术瓶颈,提升思维能力
`fail: (err) => {`
`//do something if err happend`
`})`
`//层层回调,麻烦
复制代码

结语

感谢您的观看,如有不足之处,欢迎批评指正。

本次给大家推荐一个免费的学习群,里面概括移动应用网站开发,css,html,webpack,vue node angular以及面试资源等。 对web开发技术感兴趣的同学,欢迎加入Q群:864305860,不管你是小白还是大牛我都欢迎,还有大牛整理的一套高效率学习路线和教程与您免费分享,同时每天更新视频资料。 最后,祝大家早日学有所成,拿到满意offer,快速升职加薪,走上人生巅峰。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值