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

摘要:
将微信小程序的异步API转换为Promise。使用Promise处理异步操作是多么方便,无论使用它的人都知道。官方微信没有提供PromiseAPI来处理异步操作,并且有许多官方API是异步的,这使得多层异步编程回调。一旦代码变得复杂,回调就会像砸了电脑一样。因此,我编写了一个通用工具,将微信的官方异步API转换为Promise,方便处理(多个)异步操作。您可以使用:准备转换的方法并公开///utils/wx 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的一个工具库

优点:

  1. 避免小程序异步编程多次回调带来的过多回调导致逻辑不清晰,篇幅过长等问题。
  2. 借助于Promise异步编程特点,支持链式操作,像同步一样写异步。
  3. 转化后得API几乎和微信官方API一样。

使用方法:

  1. 安装
  • 使用git安装到项目根目录/module,
git clone https://github.com/tornoda/to-promise
  • 或直接下载放入项目目录下如:/module
  1. 在需要用到的地方引入
import toPromise from '/module/to-promise/src/index'
  1. 绑定微信全局对象(wx)到函数,以便可以取到微信得API
const toPromiseWx = toPromise(wx)
  1. 开始转化你需要得异步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)除去successfail后的对象。例如:

官方APIwx.getLocation(OBJECT)OBJECT接受如下属性: typealtitudesuccessfailcomplete,那么去除(successfail)后为:typealtitudecomplete

返回: (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}
})

应用场景举例

  1. 单次异步调用,参见API最后
  2. 多次异步操作调用,且每下一次调用都会用到前一次返回的结果。
    如:获得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,简化异步编程》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇linux下编译安装软件到指定目录微信小程序添加、删除class’下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

使用hibernate-jpamodelgen生成jpa的元模型

1.引入依赖 <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-jpamodelgen</artifactId> </dependency> 2.idea 的设置 在idea里设置a...

eclipse的代码格式化的个性配置

1、安装jdk a. 到http://www.oracle.com/technetwork/java/javase/downloads/index.html 下载对应版本的jdk,安装到自己电脑上。 b. 安装完成后,配置环境变量:在 我的电脑 图标上点击鼠标右键,选择 属性 > 高级 > 环境变量 > 用户变量,点击界面最下方的 新...

influxDB学习总结

1.安装    请参考http://www.cnblogs.com/zhja/p/5996191.html,    安装完毕运行influxd,http://域名:8083为控制台界面;http://域名:8086为api地址;运行influx进入命令行模式。 2.go操作influxdb   1)利用influxdb的client,github地址:gi...

JavaScript 引用类型 ( 5章 )

引用类型常被称为 “类”,但是这在JavaScript中不太合适。它是属性和方法的集合。 引用类型的值"对象"是引用类型的实例。 特殊的标识符和运算符  符号 类型 执行操作 () 函数 函数调用 new 构造函数调用 创建新对象     new 运算符用来创建一个新对象,并调用构造函数初始化它,new 是一个一元运算符,出现在构造函数的调...

WPF 大数据加载过程中的等待效果——圆圈转动

大家肯定遇到过或将要遇到加载大数据的时候,如果出现长时间的空白等待,一般人的概念会是:难道卡死了? 作为一个懂技术的挨踢技术,即使你明知道数据量太大正在加载,但是假如看不到任何动静,自己觉得还是一种很不好的体验。 之前做项目的时候有这方面的要求,我的前辈们早已给出了完美的解决方案。最近自己在努力学习,今天拿出来与大家一起分享,我想一定会有帮助的。看过之后大...

gateway + jwt 网关认证

思路: 全局过滤器对所有的请求拦截(生成token有效期30分钟,放入redis设置有效期3天。3天之类可以通过刷新接口自动刷新,超过3天需要重新登录。) 前端在调用接口之前先判断token是否过期(3o分钟),过期则先调刷新接口,换取新token, 1- 引入相关jar <dependency> <groupI...