当前位置: 首页 > 微信相关

微信小程序异步API转化Promise,简化异步编程

发布日期:2038-01-19 11:14:07 分类:微信相关 阅读()来源:网络收集

好东西要多分享:

做网站就上魔艺客
摘要:把微信小程序异步API转化为Promise。用Promise处理异步操作实际非常方便。

把微信小程序异步API转化为Promise。用Promise处理异步操作实际非常方便。微信官方没有给出Promise API来处理异步操作,而官方API异步的又非常多,这使得多异步编程会层层回调,代码一复杂,回调起来就非常复杂。如果把微信官方的异步API转化为Promise,方便处理(多)异步操作。

准备转化后的方法并暴露出

// /utils/wx-promise.js

importtoPromisefrom'/module/to-promise/src/index'

consttoPromiseWx = toPromsie(wx)

exportconstrequest = toPromiseWx('requset')

exportconstgetLocation = toPromiseWx('getLocation')

exportconstsetStorage = 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(()=>{

//保存失败

})}})

其他更多更具体用法,直接粘贴README了,如下。

to-promise是一个转换微信小程序异步API为Promise的一个工具库

优点:

避免小程序异步编程多次回调带来的过多回调导致逻辑不清晰,篇幅过长等问题。

借助于Promise异步编程特点,支持链式操作,像同步一样写异步。

转化后得API几乎和微信官方API一样。

使用方法:

安装

使用git安装到项目根目录/module,

git clonehttps://github.com/tornoda/to-promise

或直接下载放入项目目录下如:/module

在需要用到的地方引入

importtoPromisefrom'/module/to-promise/src/index'绑定微信全局对象(wx)到函数,以便可以取到微信得APIconst toPromiseWx = toPromise(wx)开始转化你需要得异步API//apiName为微信异步方法名,如对wx.request()进行转化constrequest = toPromiseWx('request')//直接使用request方法关于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)=>{//dosomethingifsucceed},

(err)=>{//dosomethingiffailed})

与下面官方调用等价

wx.getLocation({

type:'wgs84',

altitude:true,

complete:()=>{console.log('to-promsise is awesome') },

success:(res)=>{//dosomethingifsucceed},

fail:(err)=>{//dosomethingiffailed}

})


应用场景举例

单次异步调用,参见API最后

多次异步操作调用,且每下一次调用都会用到前一次返回的结果。

如:获得GPS信息后,根据GPS信息获取天气信息,取得天气信息后立马存入localStorage。


推荐阅读: 微信小程序开发教程 微信小程序




声明: 文章内容及图片部分全部摘自网络,在此分享供读者参考和借鉴,不代表酷雷的观点。文章、图片等内容如涉嫌侵权,请联系我们删除,谢谢!带有原创标签的属于酷雷原创文章,未经允许不得转载!

标签:

我要说一说

加载中~

相关推荐

您好,很高兴为您服务!
广告合作
投诉建议
联系站长

客服热线:15821432298

扫码加好友,优惠等你来!