微信小程序怎么实现异步API为Promise简化异步编程
创始人
2024-12-23 19:43:50
0次

你可以这样用:

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

// /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
})
//层层回调,如果逻辑再复杂点,可能就疯了

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...