1. 程式人生 > >把微信小程序異步API為Promise,簡化異步編程

把微信小程序異步API為Promise,簡化異步編程

.data som als ted 導致 for location 全局對象 顯示

把微信小程序異步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接受如下屬性: 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}
})

應用場景舉例

  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,簡化異步編程